目前我的代码导致间歇性的 ConcurrentModificationException 错误,可能是因为我循环遍历 HashMap 的方式:
for (Map.Entry<String, Entity> entry : entities.entrySet()) {
String key = entry.getKey();
Entity item = entry.getValue();
if (item.isDestroyed()){
entities.remove(key);
ViewManager.getInstance().removeItem(key);
//INSTRUCT THE ENTITY TO PERFORM IT'S DESTROYED BEHAVIOR item.Destroyed()
} else {
item.update(1);
ConsoleItem ci = new ConsoleItemImpl(item.getIdentifier(), item.getLocation(), ColorStringConverter.getInstance().StringToColor(item.getSide()), item.getAngle(), item.getShape(), item.toString(), item.isDestroyed(), item.isDamaged());
ViewManager.getInstance().updateItem(ci);
}
item.update(1);
}
// updateInfo call
ViewManager.getInstance().updateInfo(summary());
}
如何连续循环 HashMap 并避免 ConcurrentModificationException 错误?
最佳答案
您不能在遍历 map 时修改 map 。您要么必须复制 map ,要么使用 ConcurrentHashMap ,或使用 iterator .如果是在多线程环境下,那么可以在synchronized block 中进行修改。
另一种选择是使用 iterator .
我用下面的迭代器重写了你的 for 循环:
for(Iterator<Map.Entry<String, Entity>> iterator = entities.entrySet().iterator(); iterator.hasNext(); ){
Map.Entry<String, Entity> entry = iterator.next();
String key = entry.getKey();
Entity item = entry.getValue();
if (item.isDestroyed()){
//Notice using an iterator to remove
iterator.remove();
ViewManager.getInstance().removeItem(key);
//INSTRUCT THE ENTITY TO PERFORM IT'S DESTROYED BEHAVIOR item.Destroyed()
} else {
item.update(1);
ConsoleItem ci = new ConsoleItemImpl(item.getIdentifier(), item.getLocation(), ColorStringConverter.getInstance().StringToColor(item.getSide()), item.getAngle(), item.getShape(), item.toString(), item.isDestroyed(), item.isDamaged());
ViewManager.getInstance().updateItem(ci);
}
item.update(1);
}
我不确定连续循环 HashMap 的部分。 HashMap 具有一组有限的键,因此您通常可以遍历键集。如果您出于某种原因想要连续循环,那么您需要先告诉我们其背后的原因以及该连续循环的终止条件(它不可能真的永远,对吧?)。
关于java - 连续遍历 HashMap 需要什么代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7734544/