Sven van den Boogaart
Sven van den Boogaart

Reputation: 12331

Create ArrayList based with object based on method parameter

I have a Class with Balls.

In another class called CollectionBalls i have a collection of Balls (what a suprise)

The class CollectionBalls has a ArrayList of the type balls :

 ArrayList <Balls> myBalls;

What i want to do is when i create the object CollectionBalls is : set the ammount of balls in the parameter of the constructor.

like

public CollectionBalls(int amountOfBalls)
{
    myBalls = new ArrayList <Balls>();
    setAmountOfBalls(amountOfBalls);
}

public void setAmountOfBalls(int amountOBalls)
{
    for (int i = 0; i < amountOBalls;  i ++)
    {
        // Create a new ball
        Ball i = new Ball();
        // Add the ball to the collection of ball
        myBalls.add(i);
    }
}

but i cant create a new ball dynamicly with i.

How can i create the amount of object based on the parameter?

edit: i can rename i with something like testBall but testBall is one object then instead of 10 object like ball 1 ball 2 ball 3 right?

Upvotes: 1

Views: 136

Answers (2)

danihodovic
danihodovic

Reputation: 1265

public CollectionBalls(int amountOfBalls)
{
    myBalls = new ArrayList <Balls>();
    setAmountOfBalls(amountOfBalls);
}

public void setAmountOfBalls(int amountOBalls)
{
    for (int i = 0; i < amountOf**Registers**;  i ++)

        // Add the ball to the collection of ball
        myBalls.add(new Balls());
    }
}

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201527

I see two issues

public void setAmountOfBalls(int amountOBalls)
{
  for (int i = 0; i < amountOBalls;  i++)
  {
    // Create a new ball
    // Ball i = new Ball(); // you have a plural class name, but were trying to 
                            // make it singular here and you already have an 
                            // integer variable called i.
    Balls ball = new Balls();
    // Add the ball to the collection of ball
    myBalls.add(ball);
  }
}

Upvotes: 2

Related Questions