我正在制作一个4人团队游戏,并被要求使用子列表。以下是清单:
/**
* The list of players in this team.
*/
private final static List<Player> players = new LinkedList<Player>();
/**
* A list of players in the waiting room.
*/
private final static List<Player> waitingPlayers = new LinkedList<Player>();
我收到了这个错误:
java.util.ConcurrentModificationException
[11/25/11 3:36 PM]: at java.util.SubList.checkForComodification(Unknown Sour
ce)
[11/25/11 3:36 PM]: at java.util.SubList.listIterator(Unknown Source)
[11/25/11 3:36 PM]: at java.util.AbstractList.listIterator(Unknown Source)
[11/25/11 3:36 PM]: at java.util.SubList.iterator(Unknown Source)
[11/25/11 3:36 PM]: at java.util.AbstractCollection.contains(Unknown Source)
[11/25/11 3:36 PM]: at java.util.AbstractCollection.removeAll(Unknown Source)
此处列出的代码。
public static void enterGame(final Client c) {
if(waitingPlayers.size() < 4) {
c.sendMessage("Waiting for 4 players");
return; // not enough players
}
// Picks 4 ppl from the list
System.out.println("Starting new game");
Collections.shuffle(waitingPlayers);
System.out.println("Picking random players");
final List<Player> picked = waitingPlayers.subList(0, 4);
players.addAll(picked);
waitingPlayers.removeAll(picked);
if(players.contains(c)) {
c.sendMessage("Your on a team!");
}
}
答案 0 :(得分:12)
当基础原始列表更改时,subList变为无效。复制一份,例如使用
List<Player> picked = new ArrayList<Player>(waitingPlayers.subList(0,4));
waitingPlayers.removeAll(picked);