1. Reasons for ConcurrentModificationException,
please look at the following code first:
public class Test2 {
public static void main(String[] args) {
ArrayList<String> **al** = new ArrayList<String>(); //集合对象
al.add("hello");
al.add("world");
al.add("java");
Iterator<String> **ite** = al.iterator(); //迭代器对象
while(ite.hasNext()) {
String str = ite.next();
if("world".equals(str)) {
**al**.add("sql");
}
}
System.out.println(al);
Exception screenshot:
ArrayList al = new ArrayList(); //Collection object
Iterator ite = al.iterator(); //Iterator object
al.add("sql"); //Use the collection object to add elements in the array
Analysis of the underlying source code of Iteration:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
Object[] elementData = ArrayList.this.elementData;
elementData points to the underlying data structure. At this time, there are two references to point to. When traversing the elements, you need to add elements. The system can’t distinguish the instructions, so it reports an exception—concurrent modification exception , The reason is that the method of using the collection object is not allowed when using the iterator to traverse.
Solution:
public ListIterator<E> listIterator() {
return new ListItr(0);
}
ListItr(0); is an interface instance of ListIterator.
private class ListItr extends Itr
implements ListIterator {ListItr is an internal class of ListIterator. ListItr inherits Itr and implements the ListIterator interface. The source code analysis shows that the ListIterator method is an extension of the iterator method, which can reversibly traverse elements.
Solution code (add reverse traversal elements):
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Test2 {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>(); //集合对象
al.add("hello");
al.add("world");
al.add("java"); //Iterator<String> ite =al.iterator(); //迭代器对象
ListIterator<String>ite = al.listIterator(); //ListIterator是Iterator接口的扩展,用于解决并发修改的异常
while(ite.hasNext()){
String str = ite.next();
if("world".equals(str)){
ite.add("sql"); //使用了集合对象对数组中元素进行添加
}
}
System.out.println(al);
//逆向遍历元素
while(ite.hasPrevious()){
System.out.println(ite.previous());
}
}
}