您好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); }
有任何想法吗?
谢谢尼古拉斯
编辑: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)
编辑:更新方法
私有(private)无效update(){
boolean hitDetected = false;
if(Rect.intersects(player.getHitbox(),敌人1.getHitbox())){
hitDetected = true;
敌人1.setX(-100);
}
if(Rect.intersects(player.getHitbox(),敌人2.getHitbox())){
hitDetected = true;
敌人2.setX(-100);
}
if(Rect.intersects(player.getHitbox(),敌人3.getHitbox())){
hitDetected = true;
敌人3.setX(-100);
}
if(screenX> 1000){
if(Rect.intersects(player.getHitbox(),敌人4.getHitbox())){
hitDetected = true;
敌人4.setX(-100);
}
}
if(screenX> 1200){
if(Rect.intersects(player.getHitbox(),敌人3.getHitbox())){
hitDetected = true;
敌人5.setX(-100);
}
}
if(hitDetected){
soundPool.play(bump,1,1,0,0,1);
player.reduceShieldStrength();
如果(player.getShieldStrength() soundPool.play(destroyed,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;
}
}
最佳答案
您可能正在从列表中删除一个元素,同时在其他地方使用“for each”循环来访问它。
首先,改用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(dustList){
int numSpecs = 400;
for (int i = 0; i < numSpecs; i++) {
SpaceDust spec = new SpaceDust(screenX, screenY);
dustList.add(spec);
}
}
这种方法效率很低,但是应该可以解决您的问题。这将锁定数组列表,因此在读取或写入数组列表时无法对其进行修改。