for (Integer ballNumber : balls) {
for (Integer yballNumber : yballs) {
if (ballNumber == yballNumber) {
match++;
balls.remove(ballNumber);
yballs.remove(yballNumber);
}
}
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at PowerBall_Simulator.main(PowerBall_Simulator.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
答案 0 :(得分:2)
在使用增强型for循环进行迭代时,您无法删除元素。您可以通过显式迭代器删除。
Iterator<Integer> ballsIt = balls.iterator();
while (ballsIt.hasNext()) {
Integer ballNumber = ballsIt.next();
Iterator<Integer> yballsIt = yballs.iterator();
boolean remove = false;
while (yballsIt.hasNext()) {
Integer yballNumber = yballsIt.next();
if (ballNumber == yballNumber) {
match++;
remove = true;
yballsIt.remove();
}
}
if (remove)
ballsIt.remove();
}
请注意,您不应该删除内部循环中的两个球,因为这可能会导致尝试多次从ballNumber
删除balls
。
答案 1 :(得分:1)
当您使用交互器查看列表时,列表的结构必须保持不变,直到迭代结束。否则,迭代器将无效,并且编程语言将无法使其进一步工作。
您应该做的是保留要删除的索引列表,然后仅在迭代完成时将其删除。
答案 2 :(得分:0)
向后迭代,像这样:
for (int i=balls.size()-1; i>=0 ; i--) {
Integer ballNumber = balls.get(i);
for (int j=yballs.size()-1; j>=0; j--) {
Integer yballNumber = yballs.get(j);
if (ballNumber == yballNumber) {
match++;
balls.remove(ballNumber);
yballs.remove(yballNumber);
}
}
}
答案 3 :(得分:0)
我认为这对你来说可能更好,不是使用Iterator,而是使用更传统的方式来访问arraylists:
for (int ballNumber = 0; ballNumber < balls.size() ; ballNumber++) {
Integer ball = balls.get(ballnumber);
for (int yballNumber = 0; yballNumber < yballs.size() ; yballNumber++) {
Integer yball = yballs.get(yballnumber);
//changed if to compare balls, not indexes
if (ball == yball) {
match++;
balls.remove(ballNumber);
yballs.remove(yballNumber);
//you may need to adjust your indexes here
ballnumber--;
yballnumber--;
if(ballnumber<0)
ballnumber=0;
}
}
}
快乐的编码!如果您有任何问题,请发表评论。