Java里面的數(shù)組數(shù)據(jù)可以通過索引來獲取,那么對(duì)象呢?也是通過索引嗎?今天我們就來分析一下Java集合中獲取集合對(duì)象的方法迭代-Iterator。
本篇文章主要分析一下Java集合框架中的迭代器部分,Iterator,該源碼分析基于JDK1.8,分析工具,AndroidStudio,文章分析不足之處,還請(qǐng)指正!
一、簡(jiǎn)介
我們常常使用 JDK 提供的迭代接口進(jìn)行 Java 集合的迭代。
1
2
3
4
5
|
Iterator iterator = list.iterator(); while (iterator.hasNext()){ String string = iterator.next(); //do something } |
上面便是迭代器使用的基本模板,迭代其實(shí)我們可以簡(jiǎn)單地理解為遍歷,是一個(gè)標(biāo)準(zhǔn)化遍歷各類容器里面的所有對(duì)象的方法類。它總是控制 Iterator,向它發(fā)送”向前”,”向后”,”取當(dāng)前元素”的命令,就可以間接遍歷整個(gè)集合。在 Java 中 Iterator 為一個(gè)接口,它只提供了迭代了基本規(guī)則:
1
2
3
4
5
6
7
8
9
10
|
public interface Iterator<E> { //判斷容器內(nèi)是否還有可供訪問的元素 boolean hasNext(); //返回迭代器剛越過的元素的引用,返回值是 E E next(); //刪除迭代器剛越過的元素 default void remove() { throw new UnsupportedOperationException( "remove" ); } } |
上面便是迭代器的基本申明,我們通過具體的集合來分析。
二、集合分類
2.1 ArrayList的Iterator
我們通過分析ArrayList的源碼可以知道,在 ArrayList 內(nèi)部首先是定義一個(gè)內(nèi)部類 Itr,該內(nèi)部類實(shí)現(xiàn) Iterator 接口,如下:
1
2
3
|
private class Itr implements Iterator<E> { //.... } |
在內(nèi)部類實(shí)現(xiàn)了Iterator接口,而ArrayList的Iterator是返回的它的內(nèi)部類Itr,所以我們主要看看Itr是如何實(shí)現(xiàn)的。
1
2
3
|
public Iterator<E> iterator() { return new Itr(); } |
接下來我們分析一下它的內(nèi)部類Itr的實(shí)現(xiàn)方式。
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
|
private class Itr implements Iterator<E> { protected int limit = ArrayList. this .size; int cursor; // index of next element to return int lastRet = - 1 ; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor < limit; } @SuppressWarnings ( "unchecked" ) public E next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); int i = cursor; if (i >= limit) 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(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); try { ArrayList. this .remove(lastRet); cursor = lastRet; lastRet = - 1 ; expectedModCount = modCount; limit--; } 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 ; if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } |
首先我們來分析一下定義的變量:
1
2
3
4
5
|
protected int limit = ArrayList. this .size; int cursor; // index of next element to return int lastRet = - 1 ; // index of last element returned; -1 if no such int expectedModCount = modCount; |
其中,limit是當(dāng)前ArrayList的大小,cursor代表的是下一個(gè)元素的索引,而lastRet是上一個(gè)元素的索引,沒有的話就返回-1,expectedModCount沒什么多大用處。我們接著分析看迭代的時(shí)候怎么判斷有沒有后繼元素的。
1
2
3
|
public boolean hasNext() { return cursor < limit; } |
很簡(jiǎn)單,就是判斷下一個(gè)元素的索引有沒有到達(dá)數(shù)組的容量大小,達(dá)到了就沒有了,到頭了!
接著,我們?cè)诜治鲆幌芦@取當(dāng)前索引的元素的方法next
1
2
3
4
5
6
7
8
9
10
11
12
|
public E next() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); int i = cursor; if (i >= limit) throw new NoSuchElementException(); Object[] elementData = ArrayList. this .elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1 ; return (E) elementData[lastRet = i]; } |
在next方法中為什么要判斷modCount呢?即用來判斷遍歷過程中集合是否被修改過。modCount 用于記錄 ArrayList 集合的修改次數(shù),初始化為 0,,每當(dāng)集合被修改一次(結(jié)構(gòu)上面的修改,內(nèi)部update不算),如 add、remove 等方法,modCount + 1,所以如果 modCount 不變,則表示集合內(nèi)容沒有被修改。該機(jī)制主要是用于實(shí)現(xiàn) ArrayList 集合的快速失敗機(jī)制,在 Java 的集合中,較大一部分集合是存在快速失敗機(jī)制的。所以要保證在遍歷過程中不出錯(cuò)誤,我們就應(yīng)該保證在遍歷過程中不會(huì)對(duì)集合產(chǎn)生結(jié)構(gòu)上的修改(當(dāng)然 remove 方法除外),出現(xiàn)了異常錯(cuò)誤,我們就應(yīng)該認(rèn)真檢查程序是否出錯(cuò)而不是 catch 后不做處理。上面的代碼比較簡(jiǎn)單,就是返回索引處的數(shù)組值。
對(duì)于ArrayList的迭代方法,主要是判斷索引的值和數(shù)組的大小進(jìn)行比較,看看還沒有數(shù)據(jù)可以遍歷了,然后再依次獲取數(shù)組中的值,而已,主要抓住各個(gè)集合的底層實(shí)現(xiàn)方式即可進(jìn)行迭代。
接下來我們?cè)诜治鲆幌翲ashMap的Iterator的方法,其他方法類似,只要抓住底層實(shí)現(xiàn)方式即可。
2.2 HashMap的Iterator
在HashMap中,也有一個(gè)類實(shí)現(xiàn)了Iterator接口,只不過是個(gè)抽象類,HashIterator,我們來看看它的實(shí)現(xiàn)方式。
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
|
private abstract class HashIterator<E> implements Iterator<E> { HashMapEntry<K,V> next; // next entry to return int expectedModCount; // For fast-fail int index; // current slot HashMapEntry<K,V> current; // current entry HashIterator() { expectedModCount = modCount; if (size > 0 ) { // advance to first entry HashMapEntry[] t = table; while (index < t.length && (next = t[index++]) == null ) ; } } public final boolean hasNext() { return next != null ; } final Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); HashMapEntry<K,V> e = next; if (e == null ) throw new NoSuchElementException(); if ((next = e.next) == null ) { HashMapEntry[] t = table; while (index < t.length && (next = t[index++]) == null ) ; } current = e; return e; } public void remove() { if (current == null ) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); Object k = current.key; current = null ; HashMap. this .removeEntryForKey(k); expectedModCount = modCount; } } |
同樣,它也定義了一個(gè)變量
1
2
3
4
|
HashMapEntry<K,V> next; // next entry to return int expectedModCount; // For fast-fail int index; // current slot HashMapEntry<K,V> current; // current entry |
next代表下一個(gè)entry的節(jié)點(diǎn),expectedModCount同樣是用于判斷修改狀態(tài),用于集合的快速失敗機(jī)制。index代表當(dāng)前索引,current當(dāng)前所索引所代表的節(jié)點(diǎn)entry,我們來看看如何判斷是否還有下一個(gè)元素的值的。
1
2
3
|
public final boolean hasNext() { return next != null ; } |
很簡(jiǎn)單就是判斷next是否為null,為null的話就代表沒有數(shù)據(jù)了。
接著分析獲取元素的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
final Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); HashMapEntry<K,V> e = next; if (e == null ) throw new NoSuchElementException(); // 一個(gè)Entry就是一個(gè)單向鏈表 // 若該Entry的下一個(gè)節(jié)點(diǎn)不為空,就將next指向下一個(gè)節(jié)點(diǎn); // 否則,將next指向下一個(gè)鏈表(也是下一個(gè)Entry)的不為null的節(jié)點(diǎn)。 if ((next = e.next) == null ) { HashMapEntry[] t = table; while (index < t.length && (next = t[index++]) == null ) ; } current = e; return e; } |
以上便是一些具體集合實(shí)例的迭代方法實(shí)現(xiàn)原理,同理可以分析其他集合的實(shí)現(xiàn)方式。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。