在Iterator迭代的时候,
不能用list.remove(index)直接删除,将产生异常
可以用iterator.remove();
代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class MyIterator {
List<String> list = new ArrayList<String>(5);
public void add() {
list.addAll(Arrays.asList("1", "2", "3", "4", "5"));
}
public static void main(String args[]) {
MyIterator myIt = new MyIterator();
myIt.add();
Iterator<String> iter = myIt.list.iterator();
int i = 0;
while (iter.hasNext()) {
String s = (String) iter.next();
System.out.println("" + s);
if (s.equals("2")) {
iter.remove();
}
//这一行将导致异常 java.util.ConcurrentModificationException
if (s.equals("3")) {
myIt.list.remove(i);
}
i++;
}
myIt.list.remove(2);
System.out.println(myIt.list);
}
}
异常:
1
2
3
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:782)
at java.util.ArrayList$Itr.next(ArrayList.java:754)
at MyIterator.main(MyIterator.java:22)