public static void main(String[] args) { Collectionl = new ArrayList (); for (int i=0; i < 10; ++i) { l.add(new Integer(4)); l.add(new Integer(5)); l.add(new Integer(6)); } for (Integer i : l) { if (i.intValue() == 5) { l.remove(i); } } System.out.println(l);}
会出现异常
java.util.ConcurrentModificationException
解决方法如下:
我们可以使用Iterator.remove()
比如:
Listlist = new ArrayList<>();// This is a clever way to create the iterator and call iterator.hasNext() like// you would do in a while-loop. It would be the same as doing:// Iterator iterator = list.iterator();// while (iterator.hasNext()) {for (Iterator iterator = list.iterator(); iterator.hasNext();) { String string = iterator.next(); if (string.isEmpty()) { // Remove the current element from the iterator and the list. iterator.remove(); }}
注意:遍历集合时,Iterator.remove是唯一的安全方法删除元素
以退为进:
public static void main(String[] args){ Collectionl = new ArrayList (); Collection itemsToRemove = new ArrayList (); for (int i=0; i < 10; ++i) { l.add(new Integer(4)); l.add(new Integer(5)); l.add(new Integer(6)); } for (Integer i : l) { if (i.intValue() == 5) itemsToRemove.add(i); } l.removeAll(itemsToRemove); System.out.println(l);}