public abstract class AbstractList<E>{
//操作数(操作了添加数据、删除数据,操作数都会++)
protected transient int modCount = 0;//5
}
public class ArrayList<E> extends AbstractList<E> implements List<E>{
//容器
transient Object[] elementData;
//长度(指针)
private int size;//4
public boolean add(E e) {
ensureCapacityInternal(size + 1);//判断是否扩容
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;//改变了操作数
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
public Iterator<E> iterator() {
return new Itr();
}
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;
}
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
}
//成员内部类(因为该类使用到了外部类的成员属性,所以该类才是成员内部类)
private class Itr implements Iterator<E> {
int cursor; // 游标 - 1
int lastRet = -1; // -1
int expectedModCount = modCount;//内部操作数 - 5
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//判断操作数不等于内部操作数就报错
int i = cursor;//i = 1
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification(); //判断操作数 不等于 内部操作数就报错
try {
//依赖于ArrayList的remove
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
//重新将操作数赋值给内部操作数
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
//判断操作数 不等于 内部操作数就报错
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
ArrayList<String> list = new ArrayList<>();
list.add("麻生希");
list.add("椎名空");
list.add("天使萌");
list.add("爱田奈奈");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String element = it.next();
if(element.equals("椎名空")){
//ConcurrentModificationException - 当前修改异常
list.remove(element);
}
}
for (String element : list) {
System.out.println(element);
}
看底层源码一定要找场景