我遇到静态arraylists的问题。
我有一个带字符串的播放器类。
public Player (String s) {
myPlayerName = s;
myPlayerScore = 0;
}
我有一个静态的玩家角色和一个静态的字符串数组。
static final ArrayList <Player> MY_PLAYER_LIST = new ArrayList<Player>();
static final String [] TEST_PLAYER_LIST = {"adam", "eve", "john", "mary",};
我有一个填充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());
}
}
然而,我得到的输出是;
Before - 0
Player: adam
Player: eve
Player: john
Player: mary
After - 4
Player: mary
Player: mary
Player: mary
Player: mary
有谁能帮助我理解我做错了什么?
答案 0 :(得分:5)
确保Player类看起来如下:
public class Player{
private String myPlayerName;
private int myPlayerScore;
public Player (String s) {
myPlayerName = s;
myPlayerScore = 0;
}
public String getMyPlayerName() {
return myPlayerName;
}
}