本文介绍了从Java地图列表删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的Java 的ArrayList<地图<弦乐,对象>>
。什么情况下可以从中删除列表中的元素如下:
I have Java ArrayList<Map<String, Object>>
. Is it okay to remove elements from that list as follows:
for (Map<String, Object> anObject : manyObjects) {
if (anObject.get("x").equals("y")) {
manyObjects.remove(anObject);
}
}
这有什么根本性的错误,这种方法?
Is there anything fundamentally wrong with this approach?
推荐答案
您无法从列表在遍历它与增强的for循环删除元素,因为它会抛出一个CuncurrentModificationException。你可以使用一个明确的迭代器,而非:
You can't removes elements from a List while iterating over it with the enhanced for loop, since it will throw a CuncurrentModificationException. You can use an explicit iterator instead :
Iterator<Map<String, Object>> iter = manyObjects.iterator();
while (iter.hasNext()) {
Map<String, Object> anObject = iter.next();
if (anObject.get("x").equals("y")) {
iter.remove();
}
}
这篇关于从Java地图列表删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!