[英]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. 我有一个静态的播放器arraylist和一个静态的字符串数组。
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. 我有一个填充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? 谁能帮我了解我在做什么错?
Make sure that the Player class looks as follows: 确保Player类如下所示:
public class Player{
private String myPlayerName;
private int myPlayerScore;
public Player (String s) {
myPlayerName = s;
myPlayerScore = 0;
}
public String getMyPlayerName() {
return myPlayerName;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.