Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for loop to create n amount of object

Tags:

java

arraylist

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

like image 665
Sizemj Avatar asked Sep 13 '26 22:09

Sizemj


1 Answers

//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)

like image 52
Bozho Avatar answered Sep 16 '26 14:09

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!