激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java集合框架中迭代器Iterator解析

Java集合框架中迭代器Iterator解析

2020-08-31 14:13Java開發(fā)-擱淺 Java教程

這篇文章主要為大家簡單介紹了Java集合框架中迭代器Iterator的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下

Java里面的數組數據可以通過索引來獲取,那么對象呢?也是通過索引嗎?今天我們就來分析一下Java集合中獲取集合對象的方法迭代-Iterator。

本篇文章主要分析一下Java集合框架中的迭代器部分,Iterator,該源碼分析基于JDK1.8,分析工具,AndroidStudio,文章分析不足之處,還請指正!

一、簡介

我們常常使用 JDK 提供的迭代接口進行 Java 集合的迭代。

?
1
2
3
4
5
Iterator iterator = list.iterator();
     while(iterator.hasNext()){
       String string = iterator.next();
       //do something
     }

上面便是迭代器使用的基本模板,迭代其實我們可以簡單地理解為遍歷,是一個標準化遍歷各類容器里面的所有對象的方法類。它總是控制 Iterator,向它發(fā)送”向前”,”向后”,”取當前元素”的命令,就可以間接遍歷整個集合。在 Java 中 Iterator 為一個接口,它只提供了迭代了基本規(guī)則:

?
1
2
3
4
5
6
7
8
9
10
  public interface Iterator<E> {
  //判斷容器內是否還有可供訪問的元素
  boolean hasNext();
  //返回迭代器剛越過的元素的引用,返回值是 E
  E next();
  //刪除迭代器剛越過的元素
  default void remove() {
    throw new UnsupportedOperationException("remove");
  }
}

上面便是迭代器的基本申明,我們通過具體的集合來分析。

二、集合分類

2.1 ArrayList的Iterator

我們通過分析ArrayList的源碼可以知道,在 ArrayList 內部首先是定義一個內部類 Itr,該內部類實現(xiàn) Iterator 接口,如下:

?
1
2
3
private class Itr implements Iterator<E> {
  //....
}

在內部類實現(xiàn)了Iterator接口,而ArrayList的Iterator是返回的它的內部類Itr,所以我們主要看看Itr是如何實現(xiàn)的。

?
1
2
3
public Iterator<E> iterator() {
  return new Itr();
}

接下來我們分析一下它的內部類Itr的實現(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是當前ArrayList的大小,cursor代表的是下一個元素的索引,而lastRet是上一個元素的索引,沒有的話就返回-1,expectedModCount沒什么多大用處。我們接著分析看迭代的時候怎么判斷有沒有后繼元素的。

?
1
2
3
public boolean hasNext() {
    return cursor < limit;
}

很簡單,就是判斷下一個元素的索引有沒有到達數組的容量大小,達到了就沒有了,到頭了!

接著,我們在分析一下獲取當前索引的元素的方法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 集合的修改次數,初始化為 0,,每當集合被修改一次(結構上面的修改,內部update不算),如 add、remove 等方法,modCount + 1,所以如果 modCount 不變,則表示集合內容沒有被修改。該機制主要是用于實現(xiàn) ArrayList 集合的快速失敗機制,在 Java 的集合中,較大一部分集合是存在快速失敗機制的。所以要保證在遍歷過程中不出錯誤,我們就應該保證在遍歷過程中不會對集合產生結構上的修改(當然 remove 方法除外),出現(xiàn)了異常錯誤,我們就應該認真檢查程序是否出錯而不是 catch 后不做處理。上面的代碼比較簡單,就是返回索引處的數組值。

對于ArrayList的迭代方法,主要是判斷索引的值和數組的大小進行比較,看看還沒有數據可以遍歷了,然后再依次獲取數組中的值,而已,主要抓住各個集合的底層實現(xiàn)方式即可進行迭代。

接下來我們在分析一下HashMap的Iterator的方法,其他方法類似,只要抓住底層實現(xiàn)方式即可。

2.2 HashMap的Iterator

在HashMap中,也有一個類實現(xiàn)了Iterator接口,只不過是個抽象類,HashIterator,我們來看看它的實現(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;
   }
 }

同樣,它也定義了一個變量

?
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代表下一個entry的節(jié)點,expectedModCount同樣是用于判斷修改狀態(tài),用于集合的快速失敗機制。index代表當前索引,current當前所索引所代表的節(jié)點entry,我們來看看如何判斷是否還有下一個元素的值的。

?
1
2
3
public final boolean hasNext() {
  return next != null;
}

很簡單就是判斷next是否為null,為null的話就代表沒有數據了。

接著分析獲取元素的方法

?
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();
  // 一個Entry就是一個單向鏈表
  // 若該Entry的下一個節(jié)點不為空,就將next指向下一個節(jié)點;
  // 否則,將next指向下一個鏈表(也是下一個Entry)的不為null的節(jié)點。
  if ((next = e.next) == null) {
    HashMapEntry[] t = table;
    while (index < t.length && (next = t[index++]) == null)
      ;
  }
  current = e;
  return e;
}

以上便是一些具體集合實例的迭代方法實現(xiàn)原理,同理可以分析其他集合的實現(xiàn)方式。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 精品一区二区在线观看视频 | 日韩视频在线不卡 | 国产精品成人免费一区久久羞羞 | 欧美一级www片免费观看 | 性少妇videosexfreexx入片 | 香蕉久久久精品 | 久久久久国产视频 | 中文字幕 亚洲一区 | 国产69久久精品成人看 | 深夜影院一级毛片 | 国产乱一区二区三区视频 | 天天干导航 | 最近日本电影hd免费观看 | 亚洲五码在线观看视频 | 婷婷一区二区三区 | 久久久精品视 | 在线亚州 | 黄色片快播 | 亚洲视频在线一区二区 | 国产成人精品网站 | 欧美成人视| 91精品国产91久久久久久蜜臀 | 视频一区国产精品 | 免费a级片在线观看 | 成人福利视频 | 成av人在线观看 | 最近日本电影hd免费观看 | 欧美精品日日鲁夜夜添 | 欧美雌雄另类xxxxx | 污片视频网站 | 免费黄色在线 | www.99tv| 中文字幕在线播放视频 | 中文字幕国产亚洲 | v片在线看 | 黄色小视频免费在线观看 | 亚洲一区免费观看 | 一区二区三区四区高清视频 | 美女在线观看视频一区二区 | 羞羞视频在线免费 | 欧美黄一级 |