Question

I need some help. I want to create a for loop that creates n number of objects of a class, and then adds them into an arraylist. Something like this:

//Player is a custom class 
ArrayList<Player> numberofPlayersArray;
numberofPlayersArray = new ArrayList<Player>();

//n is a variable for the number of Player class objects that I want to create
  for(int i = 0; i < n; i++)
  {

    //this is what I can come up with but I am missing something 

     Player p;
     p = new Player
     numberofPlayersArray.add(p);

    }

Any help would be appreciated

Was it helpful?

Solution

//Player is a custom class 
ArrayList<Player> numberofPlayersArray = new ArrayList<Player>(n);

//n is a variable for the number of Player class objects that I want to create
for(int i = 0; i < n; i++) {

    //this is what I can come up with but I am missing something 

     Player p = new Player();
     numberofPlayersArray.add(p);
}

Note that it's better to initialize the ArrayList with the size, if it is known (as in your case)

OTHER TIPS

Your code looks syntactically correct with one exception.

Change

p = new Player

to

p = new Player();

I'm assuming the variable n is declared and initialized and the Player class is defined with an argless constructor.

I don't see a problem here, just do

p = new Player();

(but this might just have been a typo) and the playerlist will be populated with n different Player objects.

Note, that I'm just assuming, you want to use the default constructor for Player.

Naming hint: you shouldn't name a List '..Array', unless you want to confuse yourself ;) Just name it '..List'

Don't forget to code to the interface (rather than the concrete class).

List<Player> numberofPlayers = new ArrayList<Player>(n);

Forgetting to do this (or not knowing about it) is a common beginners mistake.

If you decide to switch to an alternative list implementation later on (LinkedList or maybe a Google Collection or an Apache Commons Collection list) you won't have to change every reference to the list - just the initial allocation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top