从ArrayList中删除对象报java.util.ConcurrentModificationException异常解决
2011-05-23 09:16
483 查看
今天遍历一个ArrayList去查找某项是否存在,如果存在的话就从列表中删除,方法如下:
for(Person p : persons){
if(p.getName().equals(name))
persons.remove(p);
}
结果出现java.util.ConcurrentModificationException错误,一个并发的错误,上网google了一下,有人给出的解释是如果一边遍历ArrayList一边删除当前元素会引发java.util.ConcurrentModificationException 即”要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。”
解决方法1:
//使用java.util.Iterator
for(Iterator it = list.iterator(); it.hasNext();){
Integer i = (Integer)it.next();
it.remove();
}
解决方法2:
for(int i = 0; i<persons.size(); i++){
if(persons.get(i).getName().equals(name))
persons.remove(i);
}
方法2不适合大型数组
for(Person p : persons){
if(p.getName().equals(name))
persons.remove(p);
}
for(Person p : persons){ if(p.getName().equals(name)) persons.remove(p); }
结果出现java.util.ConcurrentModificationException错误,一个并发的错误,上网google了一下,有人给出的解释是如果一边遍历ArrayList一边删除当前元素会引发java.util.ConcurrentModificationException 即”要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。”
解决方法1:
//使用java.util.Iterator
for(Iterator it = list.iterator(); it.hasNext();){
Integer i = (Integer)it.next();
it.remove();
}
//使用java.util.Iterator for(Iterator it = list.iterator(); it.hasNext();){ Integer i = (Integer)it.next(); it.remove(); }
解决方法2:
for(int i = 0; i<persons.size(); i++){
if(persons.get(i).getName().equals(name))
persons.remove(i);
}
for(int i = 0; i<persons.size(); i++){ if(persons.get(i).getName().equals(name)) persons.remove(i); }
方法2不适合大型数组
相关文章推荐
- 从ArrayList中删除对象报java.util.ConcurrentModificationException异常解决
- 从ArrayList中删除对象报java.util.ConcurrentModificationException异常解决
- java.util.ConcurrentModificationException 解决办法(使用迭代器时出现异常)
- ArrayList 的java.util.ConcurrentModificationException异常?
- java.util.ConcurrentModificationException异常解决
- 关于Map表循环过程删除操作出现的java.util.ConcurrentModificationException 异常
- java.util.ConcurrentModificationException异常解决方法
- Map中删除数据报:java.util.ConcurrentModificationException异常
- 关于出现List的java.util.ConcurrentModificationException异常问题的解决
- java.util.ConcurrentModificationException ,遍历集合并同时修改集合,并发造成的异常解决办法
- java.util.ConcurrentModificationException异常的解决办法
- java.util.ConcurrentModificationException 异常的解决方法
- java.util.ConcurrentModificationException异常解决方法
- java.util.ConcurrentModificationException异常的解决实例
- 遍历Map时抛出java.util.ConcurrentModificationException异常的解决办法
- java.util.ConcurrentModificationException异常参考解决方法
- 遍历集合时删除元素,抛出java.util.ConcurrentModificationException的解决办法
- java.util.ConcurrentModificationException异常 解决方法
- 遍历Map时抛出java.util.ConcurrentModificationException异常的解决办法
- JAVA List 一边遍历一边删除元素,报java.util.ConcurrentModificationException异常