ArrayList源码解析之iterator、listIterator
ArrayList的遍历方式有多种,本文主要对Iterator、ListIterator两种迭代器的源码进行分析。
一、Iterator源码分析
1 | public Iterator<E> iterator() { |
iterator() 方法返回的是一个内部类Itr,接下来看看Itr: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
83private 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;
Itr() {}
// 是否有下个元素
public boolean hasNext() {
return cursor != size;
}
// 获取元素,每次调用next()方法前,先调用hasNext()方法,否则可能会有异常抛出
("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;
// 将lastRet的值设为当前下标,并返回元素
return (E) elementData[lastRet = i];
}
public void remove() {
// 下标是否越界
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
// 调用ArrayList的方法进行删除操作
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
/*
* ArrayList.this.remove(lastRet)会使modCount的值发生变化,
* 这里需要手动使二者的值保持一致。
* 使用迭代器的过程不能使用ArrayList的remove方法,
* 否则会抛出ConcurrentModificationException异常
*/
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 循坏剩下的元素,如果循坏完成,同一个Iterator对象,第二次调用无意义
("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() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
分析Itr的源码可以得出,Itr实现了集合的顺序遍历,可以使用remove()方法操作集合。
二、ListIterator
1 | public ListIterator<E> listIterator() { |
listIterator() 方法返回的是ArrayList的一个内部类ListItr,继承了Itr类实现了Iterator接口。ListItr中增加了previous()、add()、set()等方法。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
68private class ListItr extends Itr implements ListIterator<E> {
// 构造函数,可以指定遍历的起始位置
ListItr(int index) {
super();
cursor = index;
}
// 是否有上一个元素
public boolean hasPrevious() {
return cursor != 0;
}
// 获取下个元素的下标
public int nextIndex() {
return cursor;
}
// 获取上个元素的下标
public int previousIndex() {
return cursor - 1;
}
// 获取上个元素,调用该方法时,应该调用hasPrevious()判断是否有上个元素,否则可能会抛出异常
("unchecked")
public E previous() {
checkForComodification();
// 上个元素的下标
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
// 在当前lastRet位置替换元素
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
// 调用ArrayList的set方法,将当前lastRet下标处的值替换为输入值
// set方法不会使modCount的值发生变化
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 指定位置添加元素
public void add(E e) {
checkForComodification();
try {
int i = cursor;
// 指定位置增加元素,该操作会使modCount的值发生变化
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
从ListItr的源码中可以看出,在Itr的基础上,ListItr增加了向前、从指定位置开始这两种遍历方式,增加了set()、add()方法对集合的数据进行操作,功能更加强大。