今天遍历一个ArrayList去查找某项是否存在,如果存在的话就从列表中删除,方法如下:
- for(Personp: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(Iteratorit=list.iterator();it.hasNext();){
- Integeri=(Integer)it.next();
- it.remove();
- }
//使用java.util.Iterator for(Iterator it = list.iterator(); it.hasNext();){ Integer i = (Integer)it.next(); it.remove(); }
解决方法2:
- for(inti=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不适合大型数组