Walkerbo Walkerbo - 6 months ago 11
Java Question

Static ArrayList - populate enhanced loop

I am facing a problem with static arraylists.

I have a player class that takes a string.

public Player (String s) {
myPlayerName = s;
myPlayerScore = 0;
}


I have a static arraylist of players and a static array of strings.

static final ArrayList <Player> MY_PLAYER_LIST = new ArrayList<Player>();
static final String [] TEST_PLAYER_LIST = {"adam", "eve", "john", "mary",};


I have a function that populates the arraylist.

public void buildPlayerList () {
System.out.println("Before - " + MY_PLAYER_LIST.size());
for (String temp: TEST_PLAYER_LIST) {
Player tempPlayer = new Player(temp);
MY_PLAYER_LIST.add(tempPlayer);
System.out.println("Player: " + tempPlayer.getMyPlayerName());
}
System.out.println("After - " + MY_PLAYER_LIST.size());
for (Player temp: MY_PLAYER_LIST) {
System.out.println(temp.getMyPlayerName());
}
}


However the output I get is;

Before - 0
Player: adam
Player: eve
Player: john
Player: mary
After - 4
Player: mary
Player: mary
Player: mary
Player: mary


Can anyone please help me understand what I am doing wrong?

Answer

Make sure that the Player class looks as follows:

public class Player{
    private  String myPlayerName;
    private int myPlayerScore;
    public Player (String s) {    
        myPlayerName = s;
        myPlayerScore = 0;
    }
    public String getMyPlayerName() {
        return myPlayerName;
    }           
}