我正在迭代两个Orb对象列表
目前,当我浏览这两个列表时,我会在遍历它们时添加和删除Orb对象。
//first I iterate through the "friendly" orb list.
for(orbIterator = friendlyOrbs.listIterator(); orbIterator.hasNext();) {
//I have only included what I (think) is the relevant code.
Orb tempOrb = orbIterator.next(); //Set a reference to the current orb object so I can update it and use its properties.
//Some drawing stuff I don't include.
//The orb is not dead
int orbResult = tempOrb.Update(); //Updates the orb object and returns its current state.
if(orbResult == 0) {
} else if(orbResult == 2) {
//Died a natural death
//Stuff to do when the orb dies naturally.
orbIterator.remove();
} else if(orbResult == 3) {
//Killed by player.
//stuff to do when player kills orb.
orbIterator.remove();
orbIterator.add(new Orb(...));
}
}
现在这就是我如何遍历"敌人" orb list:
for(orbIterator = enemyOrbs.listIterator(); orbIterator.hasNext();) {
Orb tempOrb = orbIterator.next();
int orbResult = tempOrb.Update();
if(orbResult == 0) {
} else if (orbResult == 2) {
//Enemy orb died a natural death.
orbIterator.remove();
enemyOrbs.add(...);
} else if(orbResult == 3) {
//Enemy orb killed by player.
orbIterator.remove();
} else {
//Draw the orb.
}
}
我还有两个计时器任务(一个用于产生友好的星球,一个用于产生敌人的球体),它设置一个布尔标志,告诉onDraw方法是否应该向屏幕添加新的球体。
//the friendly orb timertask
public static class FriendlyOrbTimerTask extends TimerTask implements Cloneable {
@Override
public void run() {
if(SystemClock.uptimeMillis() - drawCallTime < 100) {
Log.i("ADDING NEW ORB", "ADDING NEW ORB");
friendlyOrbToBeAdded = true;
friendlyOrbSpawnInterval += 250;
TIMER.schedule(this.clone(), friendlyOrbSpawnInterval);
} else {
pauseStartTime = SystemClock.uptimeMillis();
}
}
@Override
public FriendlyOrbTimerTask clone(){
return new FriendlyOrbTimerTask(); //add parameters from the current contextif needed.
}
}
这是敌人的时间任务:
public static class EnemyOrbTimerTask extends TimerTask implements Cloneable {
@Override
public void run() {
if(SystemClock.uptimeMillis() - drawCallTime < 50) {
enemyOrbToBeAdded = true;
enemyOrbSpawnInterval+= 250;
TIMER.schedule(this.clone(), enemyOrbSpawnInterval);
}
}
@Override
public EnemyOrbTimerTask clone(){
return new EnemyOrbTimerTask(); //add parameters from the current contextif needed.
}
}
以下是if语句告诉我是否应该在屏幕上添加新的orb(位于onDraw中)
//These are located right before I iterate through the lists.
if(friendlyOrbToBeAdded) {
friendlyOrbs.add(...);
friendlyOrbToBeAdded = false;
}
if(enemyOrbToBeAdded) {
enemyOrbs.add(...);
enemyOrbToBeAdded = false;
}
问题是有时我的应用程序会在以下行中随机崩溃:
Orb tempOrb = orbIterator.next(); //This is in the enemyOrb iterator loop.
它提供了例外:java.util.ConcurrentModificationException
我不知道为什么会这样,因为我使用的是listIterator.add()
和listIterator.remove()
,这可以让我避免这些例外。
答案 0 :(得分:1)
如果您的复制粘贴准确,那么我认为这就是问题所在:
for(orbIterator = enemyOrbs.listIterator(); orbIterator.hasNext();) {
...
enemyOrbs.add(...);
...
}
在您进行迭代时,您可以在集合上调用add
。