Hello stackoverflow社区, 我需要一些帮助。这个ConcurrentModificationException错误让我发疯!我最近刚开始进行Android游戏开发和编程。
当我玩我的游戏时,如果我试图开始一个新游戏,那么它会完美无缺,但会有人受害。 Logcat在我的代码中显示这两行,但我不知道如何解决它,因为它们对我来说是正确的:/
public void run() {
while (playing) {
update();
draw(); //the draw-method is marked
control(); } }
在我的绘画方法中:
// I draw the SpaceDust from an ArrayList
paint.setColor(Color.argb(255, 255, 255, 255));
for (SpaceDust sd : dustList) {
canvas.drawPoint(sd.getX(), sd.getY(), paint); }
有什么想法吗? 谢谢Niclas
编辑:LogCat输出
FATAL EXCEPTION: Thread-146798
Process: niclas.spacegame, PID: 7983
java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
at niclas.spacegame.GameActivity$TDView.update(GameActivity.java:285)
at niclas.spacegame.GameActivity$TDView.run(GameActivity.java:206)
at java.lang.Thread.run(Thread.java:818)
编辑:update-method private void update(){ boolean hitDetected = false; if(Rect.intersects(player.getHitbox(),enemy1.getHitbox())){ hitDetected = true; enemy1.setX(-100); } if(Rect.intersects(player.getHitbox(),enemy2.getHitbox())){ hitDetected = true; enemy2.setX(-100); } if(Rect.intersects(player.getHitbox(),enemy3.getHitbox())){ hitDetected = true; enemy3.setX(-100); } if(screenX> 1000){ if(Rect.intersects(player.getHitbox(),enemy4.getHitbox())){ hitDetected = true; enemy4.setX(-100); } } if(screenX> 1200){ if(Rect.intersects(player.getHitbox(),enemy3.getHitbox())){ hitDetected = true; enemy5.setX(-100); } } if(hitDetected){ soundPool.play(bump,1,1,0,0,1); player.reduceShieldStrength(); if(player.getShieldStrength()< 0){ soundPool.play(destroy,1,1,0,0,1); gameEnded = true; } }
player.update();
enemy1.update(player.getSpeed());
enemy2.update(player.getSpeed());
enemy3.update(player.getSpeed());
if(screenX > 1000) {
enemy4.update(player.getSpeed());
}
if(screenX > 1200) {
enemy5.update(player.getSpeed());
}
for (SpaceDust sd : dustList) {
sd.update(player.getSpeed());
}
if(!gameEnded) {
distanceRemaining -= player.getSpeed();
timeTaken = System.currentTimeMillis() - timeStarted;
}
if(distanceRemaining < 0){
soundPool.play(win, 1, 1, 0, 0, 1);
if(timeTaken < fastestTime) {
editor.putLong("fastestTime", timeTaken);
editor.commit();
fastestTime = timeTaken;
}
distanceRemaining = 0;
gameEnded = true;
}
}
答案 0 :(得分:1)
您可能正在从列表中删除元素,同时使用&#34;来访问每个&#34;在其他地方循环。
首先,使用Iterator,但也可以在同步块中包含对数组列表的访问权限:
替换:
for (SpaceDust sd : dustList) {
sd.update(player.getSpeed());
}
使用:
synchronized(dustList){
Iterator<SpaceDust> it = dustList.iterator();
while (it.hasNext() {
SpaceDust sd = it.next();
sd.update(player.getSpeed());
}
}
并将list修饰符包装在synchronized块中:
synchronized(dustList){
int numSpecs = 400;
for (int i = 0; i < numSpecs; i++) {
SpaceDust spec = new SpaceDust(screenX, screenY);
dustList.add(spec);
}
}
这种方法效率很低,但它可以解决您的问题。这是锁定数组列表,因此在您正在读取或写入数据时不能修改它。