Concurrent modification of iterator exception
My understanding
1. Iterator traverses collection objects
. If the collection method is used to modify the collection during the traversal process (for example, the add method of the collection is called to add an element during the traversal process )
, concurrent modification exceptions will occur
2. Iterator traverses collection objects
. If the iterator method is used to modify the collection during the traversal process (such as calling the iterator's remove method to remove an element during the traversal process )
, concurrent modification exceptions will not occur.
Code demo
public void testIteratorException() {
List<Integer> list = new ArrayList<Integer>();
// 快速添加数据 到 list对象
Collections.addAll(list, 1, 2, 100, 30, 5, 55);
System.out.println(list);
//迭代器对象it
final Iterator<Integer> it = list.iterator();
//遍历it迭代器中的值
while(it.hasNext()) {
//输出当前it的值
final Integer curr = it.next();
System.out.println(curr);
if (curr == 100) {
// 使用迭代器时候 进行 添加操作
// list.add(101); 在遍历过程中调用集合的add方法对集合进行修改
list.add(101);
}
}
System.out.println(list);
}
When we traverse to 100 elements, we call the add method of the collection, then a concurrent modification exception
will occur. This error will not occur when we call the iterator method,
as shown below
public void testListIterator() {
List<Integer> list = new ArrayList<Integer>();
// 快速添加数据 到 list对象
Collections.addAll(list, 1, 2, 100, 30, 5, 55);
System.out.println(list);
// final ListIterator<Integer> listIt = list.listIterator();
final Iterator<Integer> it = list.iterator();
while(it.hasNext()) {
final Integer curr = it.next();
System.out.println(curr);
if (curr == 100) {
// 使用迭代器时候 进行 添加操作
// it.remove(); 在遍历过程中调用迭代器的方法对集合进行修改
it.remove();
}
}
System.out.println(list);
}