国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看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開發-擱淺 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,向它發送”向前”,”向后”,”取當前元素”的命令,就可以間接遍歷整個集合。在 Java 中 Iterator 為一個接口,它只提供了迭代了基本規則:

?
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,該內部類實現 Iterator 接口,如下:

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

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

?
1
2
3
public Iterator<E> iterator() {
  return new 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
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 不變,則表示集合內容沒有被修改。該機制主要是用于實現 ArrayList 集合的快速失敗機制,在 Java 的集合中,較大一部分集合是存在快速失敗機制的。所以要保證在遍歷過程中不出錯誤,我們就應該保證在遍歷過程中不會對集合產生結構上的修改(當然 remove 方法除外),出現了異常錯誤,我們就應該認真檢查程序是否出錯而不是 catch 后不做處理。上面的代碼比較簡單,就是返回索引處的數組值。

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

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

2.2 HashMap的Iterator

在HashMap中,也有一個類實現了Iterator接口,只不過是個抽象類,HashIterator,我們來看看它的實現方式。

?
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的節點,expectedModCount同樣是用于判斷修改狀態,用于集合的快速失敗機制。index代表當前索引,current當前所索引所代表的節點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的下一個節點不為空,就將next指向下一個節點;
  // 否則,將next指向下一個鏈表(也是下一個Entry)的不為null的節點。
  if ((next = e.next) == null) {
    HashMapEntry[] t = table;
    while (index < t.length && (next = t[index++]) == null)
      ;
  }
  current = e;
  return e;
}

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

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 免费一区二区 | 一级免费网站 | 中文字幕在线导航 | 久久精品国产99国产精2020新增功能 | 嫩草视频在线 | 亚洲精久久 | 国产精品成人在线 | 欧美影视一区二区三区 | 日韩成人在线播放 | 成人欧美一区二区三区在线观看 | 91精品久久久久久9s密挑 | 99精品欧美一区二区三区 | 中文字幕日韩欧美 | 超碰97免费在线 | 一区二区国产在线观看 | 精品国产一区二区在线 | 中文字幕一区在线 | 国产欧美日韩在线观看 | 91av在线视频播放 | 红桃成人少妇网站 | 中文字幕日韩有码 | 黄色免费电影网站 | 在线观看一区视频 | 亚洲欧洲视频 | 欧美日韩一区二区在线 | 女男羞羞视频网站免费 | 国产三区av | 在线免费观看黄色 | 四虎最新紧急更新地址 | 国产精品精品视频 | 一区高清| 欧美精品久久一区 | 黄色小视频在线免费观看 | sis001亚洲原创区 | 香蕉尹人网 | 欧美日韩一区二区三区在线观看 | 国产一区二区在线看 | 成人免费一区二区三区视频软件 | 亚洲国产视频一区 | 影音先锋国产精品 | 婷婷久 |