我遇到静态数组列表的问题。
我有一个需要字符串的玩家类。
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",};
我有一个填充数组列表的函数。
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
任何人都可以帮助我理解我做错了什么吗?
最佳答案
确保 Player 类如下所示:
public class Player{
private String myPlayerName;
private int myPlayerScore;
public Player (String s) {
myPlayerName = s;
myPlayerScore = 0;
}
public String getMyPlayerName() {
return myPlayerName;
}
}
关于java - 静态ArrayList - 填充增强循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37387691/