Iterator底层源码

1
2
3
4
5
6
public abstract class AbstractList<E>{

//外部操作数
//添加元素、删除元素时会++,因为添加、删除会导致集合中的元素个数发生改变
protected transient int modCount = 0;//4
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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); // 更新modCount
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 E remove(int index) {
rangeCheck(index);

modCount++;//更新操作数
E oldValue = elementData(index);

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

return oldValue;
}

public Iterator<E> iterator() {
return new Itr();
}

private class Itr implements Iterator<E> {
//游标
int cursor; //4
//记录遍历数据的当前下标
int lastRet = -1; //3

//内部操作数(记录遍历之初的外部操作数)
int expectedModCount = modCount;//4

//size - 4
public boolean hasNext() {
return cursor != size;
}

@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//判断内部操作数和外部操作数是否一致
int i = cursor;//i - 3
if (i >= size)
throw new NoSuchElementException();

//获取外部类的对象中的elementData(数据容器)
//["小红","小绿","小黄","小黑"]
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();
}
}

final void checkForComodification() {
//判断外置操作数是否不等于内部操作数
if (modCount != expectedModCount)
//如果不等于,就说明在遍历时进行了数据的添加或删除,会导致遍历数据不准确的情况
//所以就报错 -- 并发修改异常
throw new ConcurrentModificationException();
}
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Test02 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>();

list.add("小红");
list.add("小绿");
list.add("小黄");
list.add("小黑");

Iterator<String> it = list.iterator();
while(it.hasNext()){
String next = it.next();
System.out.println(next);
}
}
}

看底层源码的技巧:设立场景