我尝试从Head第一版java书 - 第二版(第152页)中运行一个示例。这是一个游戏难题。它以网格中的Dotcoms(字符串)为目标。但是当我试图运行这个谜题时,我遇到了 Java.util.concurrentModificationException 错误。当我试图在网格中找到最后一个dotCom(String)时,我只得到了这个错误。假设我在网格中有三个字符串,如下图所示。因此,当我开始提供输入时,我能够删除(命中)前两个字符串(因为它们在arrayList中添加)但当我尝试删除最后一个字符串(在Arraylist中添加最后一个字符串)时,则得到 concurrentmodificationException < / strong>错误。示例代码和控制台日志如下所示。
那么为什么我会收到此错误以及如何删除此错误。
class DotComBust{
private GameHelper helper = new GameHelper();
private ArrayList<DotCom> dotComList = new ArrayList<DotCom>();
private int numofguesses=0;
private void setUpGame(){
DotCom one = new DotCom();
one.setNames("Pets.com");
DotCom two = new DotCom();
two.setNames("eToys.com");
DotCom three = new DotCom();
three.setNames("Go2.com");
dotComList.add(one);
dotComList.add(two);
dotComList.add(three);
System.out.println("your goal is sunk three dot coms");
System.out.println("Pets.com, eToys.com, Go2.com");
System.out.println("Try to sink them all in fewest number of guesses");
for(DotCom dotComToSet : dotComList){
ArrayList<String> newLocation = helper.placeDotCom(3);
dotComToSet.setLocationCells(newLocation);
}
}
private void startPlaying(){
while(!dotComList.isEmpty()){
String userGuess = helper.getUserInput("Enter a guess");
checkUserGuess(userGuess);
}
finishGame();
}
private void checkUserGuess(String userGuess){
numofguesses++;
String result = "miss";
for(DotCom dotComToTest : dotComList){
result = dotComToTest.checkYourself(userGuess);
if(result.equals("hit")){
break;
}
if(result.equals("kill")){
dotComList.remove(dotComToTest);
}
}
System.out.println(result);
}
private void finishGame(){
System.out.println("All the dotcoms are dead your stock is worthless");
if(numofguesses<=18){
System.out.println("It only took you" + numofguesses + "guesses");
System.out.println("You got out before your option sank");
}else{
System.out.println("Took you long enough" + numofguesses + "guesses");
System.out.println("Fish are dancing with your option");
}
}
public static void main(String[] args) {
DotComBust game = new DotComBust();
game.setUpGame();
game.startPlaying();
}
}
错误
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at DotComBust.checkUserGuess(DotComBust.java:77)
at DotComBust.startPlaying(DotComBust.java:68)
at DotComBust.main(DotComBust.java:106)
答案 0 :(得分:1)
我假设你可能有另一个同时运行的绘图线程?
在这种情况下,使用名为List
的{{1}}的线程安全实现:
CopyOnWriteArrayList
答案 1 :(得分:0)
因为在循环收集时
while(!dotComList.isEmpty()){
String userGuess = helper.getUserInput("Enter a guess");
checkUserGuess(userGuess);
}
您不能修改列表的内容,但在您的方法 checkUserGuess 中,您试图从列表中删除元素
if(result.equals("kill")){
dotComList.remove(dotComToTest);
}
这是导致ConcurrentModificationException
的原因