**
* @Author LWL
* @Date 2022/5/21 23:49
* @TODO 集合异常问题
*/
public class Test {
//迭代器内部
/*public Iterator<E> iterator() {
return new ArrayList.Itr();
}*/
/**
* expectedModCount为预期修改集合次数,modCount 为实际修改集合次数。
* Itr类中初始状态时expectedModCount和modCount 相等,在调用其中next方法时会对两者进行判断。
* 但是ArrayList中的add方法中每次添加一个元素,modCount 会自动加一。故导致在next方法中判断两者不相等,故出现并发修改异常。
*/
/*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;
@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];
}*/
/*final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}*/
//add 方法调用
/*private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}*/
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
//改成ListIterator迭代器(iterator的子接口),ListIterator可以直接往集合中添加元素,
// 因为ListItr类中有add方法,而且在方法体中会将实际修改集合的次数赋值给预期修改值。
ListIterator<Object> objectListIterator = list.listIterator();
while (objectListIterator.hasNext()) {
objectListIterator.add("");
objectListIterator.remove();
objectListIterator.set("");
}
//iterator中只有remove()操作
Iterator<Object> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.remove();
}
}
}