偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

為什么阿里不推薦使用 keySet() 遍歷HashMap?

開發(fā) 前端
HashMap相信所有學(xué)Java的都一定不會感到陌生,作為一個非常重用且非常實(shí)用的Java提供的容器,它在我們的代碼里面隨處可見。因此遍歷操作也是我們經(jīng)常會使用到的。

HashMap相信所有學(xué)Java的都一定不會感到陌生,作為一個非常重用且非常實(shí)用的Java提供的容器,它在我們的代碼里面隨處可見。因此遍歷操作也是我們經(jīng)常會使用到的。HashMap的遍歷方式現(xiàn)如今有非常多種:

  1. 使用迭代器(Iterator)。
  2. 使用 keySet() 獲取鍵的集合,然后通過增強(qiáng)的 for 循環(huán)遍歷鍵。
  3. 使用 entrySet() 獲取鍵值對的集合,然后通過增強(qiáng)的 for 循環(huán)遍歷鍵值對。
  4. 使用 Java 8+ 的 Lambda 表達(dá)式和流。

以上遍歷方式的孰優(yōu)孰劣,在《阿里巴巴開發(fā)手冊》中寫道:

圖片圖片

這里推薦使用的是entrySet進(jìn)行遍歷,在Java8中推薦使用Map.forEach()。給出的理由是遍歷次數(shù)上的不同。

  1. keySet遍歷,需要經(jīng)過兩次遍歷。
  2. entrySet遍歷,只需要一次遍歷。

其中keySet遍歷了兩次,一次是轉(zhuǎn)為Iterator對象,另一次是從hashMap中取出key所對應(yīng)的value。

其中后面一段話很好理解,但是前面這句話卻有點(diǎn)繞,為什么轉(zhuǎn)換成了Iterator遍歷了一次?

我查閱了各個平臺對HashMap的遍歷,其中都沒有或者原封不動的照搬上句話。(當(dāng)然也可能是我沒有查閱到靠譜的文章,歡迎指正)

keySet如何遍歷了兩次

我們首先寫一段代碼,使用keySet遍歷Map。

public class Test {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("k1", "v1");
        map.put("k2", "v2");
        map.put("k3", "v3");
        for (String key : map.keySet()) {
            String value = map.get(key);
            System.out.println(key + ":" + value);
        }
    }

}

運(yùn)行結(jié)果顯而易見的是

k1:v1
k2:v2
k3:v3

兩次遍歷,第一次遍歷所描述的是轉(zhuǎn)為Iterator對象我們好像沒有從代碼中看見,我們看到的后面所描述的遍歷,關(guān)注公眾號:碼猿技術(shù)專欄,回復(fù)關(guān)鍵詞:1111 獲取阿里內(nèi)部Java性能調(diào)優(yōu)手冊!也就是遍歷map,keySet()所返回的Set集合中的key,然后去HashMap中拿取value的。

Iterator對象呢?如何遍歷轉(zhuǎn)換為Iterator對象的呢?

首先我們這種遍歷方式大家都應(yīng)該知道是叫:增強(qiáng)for循環(huán),for-each

這是一種Java的語法糖~。

我們可以通過反編譯,或者直接通過Idea在class文件中查看對應(yīng)的Class文件

圖片圖片

public class Test {
    public Test() {
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap();
        map.put("k1", "v1");
        map.put("k2", "v2");
        map.put("k3", "v3");
        Iterator var2 = map.keySet().iterator();

        while(var2.hasNext()) {
            String key = (String)var2.next();
            String value = (String)map.get(key);
            System.out.println(key + ":" + value);
        }

    }
}

和我們編寫的是存在差異的,其中我們可以看到其中通過map.keySet().iterator()獲取到了我們所需要看見的Iterator對象。

那么它又是怎么轉(zhuǎn)換成的呢?為什么需要遍歷呢?我們查看iterator()方法

1. iterator()

圖片圖片

發(fā)現(xiàn)是Set定義的一個接口。返回此集合中元素的迭代器

2. HashMap.KeySet#iterator()

我們查看HashMap中keySet類對該方法的實(shí)現(xiàn)。

圖片圖片

圖片圖片

final class KeySet extends AbstractSet<K> {
    public final int size()                 { return size; }
    public final void clear()               { HashMap.this.clear(); }
    public final Iterator<K> iterator()     { returnnew KeyIterator(); }
    public final boolean contains(Object o) { return containsKey(o); }
    public final boolean remove(Object key) {
        return removeNode(hash(key), key, null, false, true) != null;
    }
    public final Spliterator<K> spliterator() {
        returnnew KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
    }
    public final void forEach(Consumer<? super K> action) {
        Node<K,V>[] tab;
        if (action == null)
            thrownew NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key);
            }
            if (modCount != mc)
                thrownew ConcurrentModificationException();
        }
    }
}

其中的iterator()方法返回的是一個KeyIterator對象,那么究竟是在哪里進(jìn)行了遍歷呢?我們接著往下看去。

3. HashMap.KeyIterator

圖片圖片

final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

這個類也很簡單:

  1. 繼承了HashIterator類。
  2. 實(shí)現(xiàn)了Iterator接口。
  3. 一個next()方法。

還是沒有看見哪里進(jìn)行了遍歷,那么我們繼續(xù)查看HashIterator類

4. HashMap.HashIterator

圖片圖片

abstract class HashIterator {
    Node<K,V> next;        // next entry to return
    Node<K,V> current;     // current entry
    int expectedModCount;  // for fast-fail
    int index;             // current slot

    HashIterator() {
        expectedModCount = modCount;
        Node<K,V>[] t = table;
        current = next = null;
        index = 0;
        if (t != null && size > 0) { // advance to first entry
            do {} while (index < t.length && (next = t[index++]) == null);
        }
    }

    public final boolean hasNext() {
        return next != null;
    }

    final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;
        if (modCount != expectedModCount)
            thrownew ConcurrentModificationException();
        if (e == null)
            thrownew NoSuchElementException();
        if ((next = (current = e).next) == null && (t = table) != null) {
            do {} while (index < t.length && (next = t[index++]) == null);
        }
        return e;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            thrownew IllegalStateException();
        if (modCount != expectedModCount)
            thrownew ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        expectedModCount = modCount;
    }
}

我們可以發(fā)現(xiàn)這個構(gòu)造器中存在了一個do-while循環(huán)操作,目的是找到一個第一個不為空的entry。

HashIterator() {
    expectedModCount = modCount;
    Node<K,V>[] t = table;
    current = next = null;
    index = 0;
    if (t != null && size > 0) { // advance to first entry
        do {} while (index < t.length && (next = t[index++]) == null);
    }
}

而KeyIterator是extendHashIterator對象的。這里涉及到了繼承的相關(guān)概念,大家忘記的可以找相關(guān)的文章看看,或者我也可以寫一篇~~dog。

例如兩個類:

public class Father {

    public Father(){
        System.out.println("father");
    }
}
public class Son extends Father{

    public static void main(String[] args) {
        Son son = new Son();
    }
}

創(chuàng)建Son對象的同時,會執(zhí)行Father構(gòu)造器。也就會打印出father這句話。

那么這個循環(huán)操作就是我們要找的循環(huán)操作了。

總結(jié)

  1. 使用keySet遍歷,其實(shí)內(nèi)部是使用了對應(yīng)的iterator()方法。
  2. iterator()方法是創(chuàng)建了一個KeyIterator對象。
  3. KeyIterator對象extendHashIterator對象。
  4. HashIterator對象的構(gòu)造方法中,會遍歷找到第一個不為空的entry。

keySet->iterator()->KeyIterator->HashIterator

責(zé)任編輯:武曉燕 來源: 碼猿技術(shù)專欄
相關(guān)推薦

2024-11-29 08:20:22

Autowired場景項(xiàng)目

2024-11-12 10:30:54

Docker部署數(shù)據(jù)庫

2024-06-04 00:10:00

開發(fā)拷貝

2020-12-15 10:00:31

MySQL數(shù)據(jù)庫text

2024-09-12 08:32:42

2024-07-29 08:20:10

2021-08-23 13:02:50

MySQLJOIN數(shù)據(jù)庫

2023-11-06 13:04:59

Python日志庫

2021-02-26 05:30:25

元素For-Each代碼

2022-01-11 10:29:32

Docker文件掛載

2021-08-04 17:20:30

阿里巴巴AsyncJava

2025-04-29 07:06:20

2021-12-08 06:53:28

HashMap面試JDK 8

2018-11-29 14:30:42

數(shù)據(jù)庫外鍵約束應(yīng)用程序

2021-01-13 09:55:29

try-catch-fJava代碼

2021-07-04 14:19:03

RabbitMQ消息轉(zhuǎn)換

2023-09-21 10:50:23

MySQL數(shù)據(jù)庫

2020-08-31 11:20:53

MySQLuuidid

2024-09-04 15:17:23

2024-03-11 11:02:03

Date類JavaAPI
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號