Reputation: 322
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
Upvotes: 3
Views: 20420
Reputation: 597164
//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++) {
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)
Upvotes: 5
Reputation: 12782
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.
Upvotes: 0
Reputation: 162821
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.
Upvotes: 5
Reputation: 114797
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'
Upvotes: 0