手撕Iterator底层源码
public abstract class AbstractList<E>{
//操作数 - 记录使用(添加、删除)集合的次数
//为什么操作数只记录添加、删除集合的次数?
//因为添加或删除会改变集合的长度,所以会被记录
protected transient int modCount = 0;//4
}
public class ArrayList<E> extends AbstractList<E> implements List<E>{
//存储数据的容器
transient Object[] elementData;//["曹操","典韦","许褚","郭嘉"]
//元素的个数/指针
private int size;//4
//e - 郭嘉
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++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
public Iterator<E> iterator() {
return new Itr();
}
//私有的成员内部类
private class Itr implements Iterator<E> {
int cursor; // 游标 -- 4
int lastRet = -1; // 当前元素的下标 - 3
int expectedModCount = modCount;//内部操作数 - 4
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//判断操作数不能与内部操作数就报错
int i = cursor;//i = 3
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.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
//操作数不等于内部操作数,就报错 -- ConcurrentModificationException
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
ArrayList<String> list = new ArrayList<>();
list.add("曹操");
list.add("典韦");
list.add("许褚");
list.add("郭嘉");
//为什么Iterator是个接口?
//Iterator的主要作用是遍历集合(ArrayList/LinkedList/Vector....)
//众多的集合的底层实现肯定是不一样的,将迭代器设计成接口,让每个集合自己去实现(内部类)
Iterator<String> it = list.iterator();
while(it.hasNext()){
String element = it.next();
System.out.println(element);
}
分析源码:一定要找场景