tags:

views:

214

answers:

4

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

+4  A: 

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.

Asaph
A: 

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'

Andreas_D
Thanks for the advice. I will keep that in mind.
Size_J
A: 
//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)

Bozho
OK now how would I call p.method(); ie: p.dosomething();
Size_J
what do you mean 'how would I call'? Just call it as you wrote.
Bozho
problem is p must be null because I get a java.lang.NullPointerException when I call p.method();
Size_J
ask another question including the entire source code and point where the null pointer exception happens.
Bozho
A: 

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.

Fortyrunner