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
//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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With