private static void extracted() {ArrayList<StudentVO> arrayList = new ArrayList<StudentVO>();arrayList.add(new StudentVO("张三", 23));arrayList.add(new StudentVO("李四", 24));arrayList.add(new StudentVO("王五", 24));Iterator<StudentVO> iterator = arrayList.iterator();while (iterator.hasNext()) {StudentVO next = iterator.next();if (next.getName().equals("王五")) {arrayList.remove(next);}}}
执行调用这段代码时候报错了
并发修改异常:
1.首先ArrayList类中有一个共享变量modCount,我们每操作一次集合这个变量都会进行加一操作(增,删,改,不包含查询)
2. 我们在开始遍历集合元素的时候,会记录此时的modCount作为expectedModCount,每次遍历一个元素的的时候都会检查,这两个参数是否相等;如果不想等就会抛出ConcurrentModifyException
添加一个元素扩容:
这个常量在进行扩容的时候,会和当前容器的最小容量进行比较,取最大的作为新容器的容量
例如当你第一次调用add进行添加元素的时候,会触发扩容
public boolean add(E e) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;}
private void ensureCapacityInternal(int minCapacity) {ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}
进入ensureCapacityInternal(size + 1);
,一开始是一个空容器所以size=0
传入的minCapacity=1
会发现minCapacity
被重新赋值为10 (DEFAULT_CAPACITY=10
)
传入ensureExplicitCapacity(minCapacity);
这时minCapacity=10
扩容的方法:
modCount++
是在父类AbstarctList
中,
后又调用了扩容grow(10)
private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;int newCapacity = oldCapacity + (oldCapacity >> 1);if (newCapacity - minCapacity < 0)newCapacity = minCapacity;if (newCapacity - MAX_ARRAY_SIZE > 0)newCapacity = hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}
其中int newCapacity = oldCapacity + (oldCapacity >> 1);
就是面试过程中经常提问到的,1.5倍
原来数组的长度
其实如果仔细阅读代码就会发现,并发修改异常不是在修改时候抛出的。而且是遍历时候next方法去检查modCount变量和预期值expectedModCount是不相等就抛出异常
@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];}
remove方法:
public boolean remove(Object o) {if (o == null) {for (int index = 0; index < size; index++)if (elementData[index] == null) {fastRemove(index);return true;}} else {for (int index = 0; index < size; index++)if (o.equals(elementData[index])) {fastRemove(index);return true;}}return false;}
调用了fastRemove:
对modCount这个变量进行了自增,这就是抛并发修改异常的关键原因。这个时候导致modCount和expectedModCount不相等
private void fastRemove(int index) {modCount++;int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null; // clear to let GC do its work}