BAT面試必問HashMap源碼分析

HashMap 簡介

HashMap 主要用來存放鍵值對,它基於哈希表的Map接口實現,是常用的Java集合之一。

JDK1.8 之前 HashMap 由 數組+鏈表 組成的,數組是 HashMap 的主體,鏈表則是主要爲了解決哈希衝突而存在的(“拉鍊法”解決衝突).JDK1.8 以後在解決哈希衝突時有了較大的變化,當鏈表長度大於閾值(默認爲 8)時,將鏈表轉化爲紅黑樹,以減少搜索時間。

底層數據結構分析

JDK1.8之前

JDK1.8 之前 HashMap 底層是 數組和鏈表 結合在一起使用也就是 鏈表散列HashMap 通過 key 的 hashCode 經過擾動函數處理過後得到 hash 值,然後通過 (n - 1) & hash 判斷當前元素存放的位置(這裏的 n 指的是數組的長度),如果當前位置存在元素的話,就判斷該元素與要存入的元素的 hash 值以及 key 是否相同,如果相同的話,直接覆蓋,不相同就通過拉鍊法解決衝突。

所謂擾動函數指的就是 HashMap 的 hash 方法。使用 hash 方法也就是擾動函數是爲了防止一些實現比較差的 hashCode() 方法 換句話說使用擾動函數之後可以減少碰撞。

JDK 1.8 HashMap 的 hash 方法源碼:

JDK 1.8 的 hash方法 相比於 JDK 1.7 hash 方法更加簡化,但是原理不變。

1

2

3

4

5

6

7

static final int hash(Object key) {

  int h;

  // key.hashCode():返回散列值也就是hashcode

  // ^ :按位異或

  // >>>:無符號右移,忽略符號位,空位都以0補齊

  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

}

對比一下 JDK1.7的 HashMap 的 hash 方法源碼.

1

2

3

4

5

6

7

8

static int hash(int h) {

    // This function ensures that hashCodes that differ only by

    // constant multiples at each bit position have a bounded

    // number of collisions (approximately 8 at default load factor).

 

    h ^= (h >>> 20) ^ (h >>> 12);

    return h ^ (h >>> 7) ^ (h >>> 4);

}

相比於 JDK1.8 的 hash 方法 ,JDK 1.7 的 hash 方法的性能會稍差一點點,因爲畢竟擾動了 4 次。

所謂 “拉鍊法” 就是:將鏈表和數組相結合。也就是說創建一個鏈表數組,數組中每一格就是一個鏈表。若遇到哈希衝突,則將衝突的值加到鏈表中即可。

10297697-af0ef296a5294339.png

JDK1.8之後

相比於之前的版本,jdk1.8在解決哈希衝突時有了較大的變化,當鏈表長度大於閾值(默認爲8)時,將鏈表轉化爲紅黑樹,以減少搜索時間。

764ae857268d65f3869fc8768314e4eb.jpeg

類的屬性:

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

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {

    // 序列號

    private static final long serialVersionUID = 362498820763181265L;   

    // 默認的初始容量是16

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;  

    // 最大容量

    static final int MAXIMUM_CAPACITY = 1 << 30;

    // 默認的填充因子

    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    // 當桶(bucket)上的結點數大於這個值時會轉成紅黑樹

    static final int TREEIFY_THRESHOLD = 8;

    // 當桶(bucket)上的結點數小於這個值時樹轉鏈表

    static final int UNTREEIFY_THRESHOLD = 6;

    // 桶中結構轉化爲紅黑樹對應的table的最小大小

    static final int MIN_TREEIFY_CAPACITY = 64;

    // 存儲元素的數組,總是2的冪次倍

    transient Node<k,v>[] table;

    // 存放具體元素的集

    transient Set<map.entry<k,v>> entrySet;

    // 存放元素的個數,注意這個不等於數組的長度。

    transient int size;

    // 每次擴容和更改map結構的計數器

    transient int modCount;  

    // 臨界值 當實際大小(容量*填充因子)超過臨界值時,會進行擴容

    int threshold;

    // 填充因子

    final float loadFactor;

}

  • loadFactor加載因子

loadFactor加載因子是控制數組存放數據的疏密程度,loadFactor越趨近於1,那麼 數組中存放的數據(entry)也就越多,也就越密,也就是會讓鏈表的長度增加,load Factor越小,也就是趨近於0,

loadFactor太大導致查找元素效率低,太小導致數組的利用率低,存放的數據會很分散。loadFactor的默認值爲0.75f是官方給出的一個比較好的臨界值。

  • threshold

threshold = capacity * loadFactor,當Size>=threshold的時候,那麼就要考慮對數組的擴增了,也就是說,這個的意思就是 衡量數組是否需要擴增的一個標準。

Node節點類源碼:

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

// 繼承自 Map.Entry<K,V>

static class Node<K,V> implements Map.Entry<K,V> {

       final int hash;// 哈希值,存放元素到hashmap中時用來與其他元素hash值比較

       final K key;//鍵

       V value;//值

       // 指向下一個節點

       Node<K,V> next;

       Node(int hash, K key, V value, Node<K,V> next) {

            this.hash = hash;

            this.key = key;

            this.value = value;

            this.next = next;

        }

        public final K getKey()        { return key; }

        public final V getValue()      { return value; }

        public final String toString() { return key + "=" + value; }

        // 重寫hashCode()方法

        public final int hashCode() {

            return Objects.hashCode(key) ^ Objects.hashCode(value);

        }

 

        public final V setValue(V newValue) {

            V oldValue = value;

            value = newValue;

            return oldValue;

        }

        // 重寫 equals() 方法

        public final boolean equals(Object o) {

            if (o == this)

                return true;

            if (o instanceof Map.Entry) {

                Map.Entry<?,?> e = (Map.Entry<?,?>)o;

                if (Objects.equals(key, e.getKey()) &&

                    Objects.equals(value, e.getValue()))

                    return true;

            }

            return false;

        }

}

樹節點類源碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {

        TreeNode<K,V> parent;  // 父

        TreeNode<K,V> left;    // 左

        TreeNode<K,V> right;   // 右

        TreeNode<K,V> prev;    // needed to unlink next upon deletion

        boolean red;           // 判斷顏色

        TreeNode(int hash, K key, V val, Node<K,V> next) {

            super(hash, key, val, next);

        }

        // 返回根節點

        final TreeNode<K,V> root() {

            for (TreeNode<K,V> r = this, p;;) {

                if ((p = r.parent) == null)

                    return r;

                r = p;

       }

HashMap源碼分析

構造方法

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

// 默認構造函數。

public More ...HashMap() {

    this.loadFactor = DEFAULT_LOAD_FACTOR; // all   other fields defaulted

 }

 

 // 包含另一個“Map”的構造函數

 public More ...HashMap(Map<? extends K, ? extends V> m) {

     this.loadFactor = DEFAULT_LOAD_FACTOR;

     putMapEntries(m, false);//下面會分析到這個方法

 }

 

 // 指定“容量大小”的構造函數

 public More ...HashMap(int initialCapacity) {

     this(initialCapacity, DEFAULT_LOAD_FACTOR);

 }

 

 // 指定“容量大小”和“加載因子”的構造函數

 public More ...HashMap(int initialCapacity, float loadFactor) {

     if (initialCapacity < 0)

         throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);

     if (initialCapacity > MAXIMUM_CAPACITY)

         initialCapacity = MAXIMUM_CAPACITY;

     if (loadFactor <= 0 || Float.isNaN(loadFactor))

         throw new IllegalArgumentException("Illegal load factor: " + loadFactor);

     this.loadFactor = loadFactor;

     this.threshold = tableSizeFor(initialCapacity);

 }

putMapEntries方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {

    int s = m.size();

    if (s > 0) {

        // 判斷table是否已經初始化

        if (table == null) { // pre-size

            // 未初始化,s爲m的實際元素個數

            float ft = ((float)s / loadFactor) + 1.0F;

            int t = ((ft < (float)MAXIMUM_CAPACITY) ?

                    (int)ft : MAXIMUM_CAPACITY);

            // 計算得到的t大於閾值,則初始化閾值

            if (t > threshold)

                threshold = tableSizeFor(t);

        }

        // 已初始化,並且m元素個數大於閾值,進行擴容處理

        else if (s > threshold)

            resize();

        // 將m中的所有元素添加至HashMap中

        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {

            K key = e.getKey();

            V value = e.getValue();

            putVal(hash(key), key, value, false, evict);

        }

    }

}

put方法

HashMap只提供了put用於添加元素,putVal方法只是給put方法調用的一個方法,並沒有提供給用戶使用。

對putVal方法添加元素的分析如下:

  • ①如果定位到的數組位置沒有元素 就直接插入。

  • ②如果定位到的數組位置有元素就和要插入的 key 比較,如果key相同就直接覆蓋,如果 key 不相同,就判斷 p 是否是一個樹節點,如果是就調用 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value) 將元素添加進入。如果不是就遍歷鏈表插入。

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

public V put(K key, V value) {

    return putVal(hash(key), key, value, falsetrue);

}

 

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

                   boolean evict) {

    Node<K,V>[] tab; Node<K,V> p; int n, i;

    // table未初始化或者長度爲0,進行擴容

    if ((tab = table) == null || (n = tab.length) == 0)

        n = (tab = resize()).length;

    // (n - 1) & hash 確定元素存放在哪個桶中,桶爲空,新生成結點放入桶中(此時,這個結點是放在數組中)

    if ((p = tab[i = (n - 1) & hash]) == null)

        tab[i] = newNode(hash, key, value, null);

    // 桶中已經存在元素

    else {

        Node<K,V> e; K k;

        // 比較桶中第一個元素(數組中的結點)的hash值相等,key相等

        if (p.hash == hash &&

            ((k = p.key) == key || (key != null && key.equals(k))))

                // 將第一個元素賦值給e,用e來記錄

                e = p;

        // hash值不相等,即key不相等;爲紅黑樹結點

        else if (p instanceof TreeNode)

            // 放入樹中

            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

        // 爲鏈表結點

        else {

            // 在鏈表最末插入結點

            for (int binCount = 0; ; ++binCount) {

                // 到達鏈表的尾部

                if ((e = p.next) == null) {

                    // 在尾部插入新結點

                    p.next = newNode(hash, key, value, null);

                    // 結點數量達到閾值,轉化爲紅黑樹

                    if (binCount >= TREEIFY_THRESHOLD - 1// -1 for 1st

                        treeifyBin(tab, hash);

                    // 跳出循環

                    break;

                }

                // 判斷鏈表中結點的key值與插入的元素的key值是否相等

                if (e.hash == hash &&

                    ((k = e.key) == key || (key != null && key.equals(k))))

                    // 相等,跳出循環

                    break;

                // 用於遍歷桶中的鏈表,與前面的e = p.next組合,可以遍歷鏈表

                p = e;

            }

        }

        // 表示在桶中找到key值、hash值與插入元素相等的結點

        if (e != null) {

            // 記錄e的value

            V oldValue = e.value;

            // onlyIfAbsent爲false或者舊值爲null

            if (!onlyIfAbsent || oldValue == null)

                //用新值替換舊值

                e.value = value;

            // 訪問後回調

            afterNodeAccess(e);

            // 返回舊值

            return oldValue;

        }

    }

    // 結構性修改

    ++modCount;

    // 實際大小大於閾值則擴容

    if (++size > threshold)

        resize();

    // 插入後回調

    afterNodeInsertion(evict);

    return null;

}

我們再來對比一下 JDK1.7 put方法的代碼

對於put方法的分析如下:

  • ①如果定位到的數組位置沒有元素 就直接插入。

  • ②如果定位到的數組位置有元素,遍歷以這個元素爲頭結點的鏈表,依次和插入的key比較,如果key相同就直接覆蓋,不同就採用頭插法插入元素。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public V put(K key, V value)

    if (table == EMPTY_TABLE) {

    inflateTable(threshold);

    if (key == null)

        return putForNullKey(value);

    int hash = hash(key);

    int i = indexFor(hash, table.length);

    for (Entry<K,V> e = table[i]; e != null; e = e.next) { // 先遍歷

        Object k;

        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {

            V oldValue = e.value;

            e.value = value;

            e.recordAccess(this);

            return oldValue;

        }

    }

 

    modCount++;

    addEntry(hash, key, value, i);  // 再插入

    return null;

}

get方法

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

public V get(Object key) {

    Node<K,V> e;

    return (e = getNode(hash(key), key)) == null null : e.value;

}

 

final Node<K,V> getNode(int hash, Object key) {

    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

    if ((tab = table) != null && (n = tab.length) > 0 &&

        (first = tab[(n - 1) & hash]) != null) {

        // 數組元素相等

        if (first.hash == hash && // always check first node

            ((k = first.key) == key || (key != null && key.equals(k))))

            return first;

        // 桶中不止一個節點

        if ((e = first.next) != null) {

            // 在樹中get

            if (first instanceof TreeNode)

                return ((TreeNode<K,V>)first).getTreeNode(hash, key);

            // 在鏈表中get

            do {

                if (e.hash == hash &&

                    ((k = e.key) == key || (key != null && key.equals(k))))

                    return e;

            while ((e = e.next) != null);

        }

    }

    return null;

}

resize方法

進行擴容,會伴隨着一次重新hash分配,並且會遍歷hash表中所有的元素,是非常耗時的。在編寫程序中,要儘量避免resize。

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

final Node<K,V>[] resize() {

    Node<K,V>[] oldTab = table;

    int oldCap = (oldTab == null) ? 0 : oldTab.length;

    int oldThr = threshold;

    int newCap, newThr = 0;

    if (oldCap > 0) {

        // 超過最大值就不再擴充了,就只好隨你碰撞去吧

        if (oldCap >= MAXIMUM_CAPACITY) {

            threshold = Integer.MAX_VALUE;

            return oldTab;

        }

        // 沒超過最大值,就擴充爲原來的2倍

        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)

            newThr = oldThr << 1// double threshold

    }

    else if (oldThr > 0// initial capacity was placed in threshold

        newCap = oldThr;

    else {

        signifies using defaults

        newCap = DEFAULT_INITIAL_CAPACITY;

        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

    }

    // 計算新的resize上限

    if (newThr == 0) {

        float ft = (float)newCap * loadFactor;

        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE);

    }

    threshold = newThr;

    @SuppressWarnings({"rawtypes","unchecked"})

        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

    table = newTab;

    if (oldTab != null) {

        // 把每個bucket都移動到新的buckets中

        for (int j = 0; j < oldCap; ++j) {

            Node<K,V> e;

            if ((e = oldTab[j]) != null) {

                oldTab[j] = null;

                if (e.next == null)

                    newTab[e.hash & (newCap - 1)] = e;

                else if (e instanceof TreeNode)

                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

                else {

                    Node<K,V> loHead = null, loTail = null;

                    Node<K,V> hiHead = null, hiTail = null;

                    Node<K,V> next;

                    do {

                        next = e.next;

                        // 原索引

                        if ((e.hash & oldCap) == 0) {

                            if (loTail == null)

                                loHead = e;

                            else

                                loTail.next = e;

                            loTail = e;

                        }

                        // 原索引+oldCap

                        else {

                            if (hiTail == null)

                                hiHead = e;

                            else

                                hiTail.next = e;

                            hiTail = e;

                        }

                    while ((e = next) != null);

                    // 原索引放到bucket裏

                    if (loTail != null) {

                        loTail.next = null;

                        newTab[j] = loHead;

                    }

                    // 原索引+oldCap放到bucket裏

                    if (hiTail != null) {

                        hiTail.next = null;

                        newTab[j + oldCap] = hiHead;

                    }

                }

            }

        }

    }

    return newTab;

}

HashMap常用方法測試

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

package map;

 

import java.util.Collection;

import java.util.HashMap;

import java.util.Set;

 

public class HashMapDemo {

 

    public static void main(String[] args) {

        HashMap<String, String> map = new HashMap<String, String>();

        // 鍵不能重複,值可以重複

        map.put("san""張三");

        map.put("si""李四");

        map.put("wu""王五");

        map.put("wang""老王");

        map.put("wang""老王2");// 老王被覆蓋

        map.put("lao""老王");

        System.out.println("-------直接輸出hashmap:-------");

        System.out.println(map);

        /**

         * 遍歷HashMap

         */

        // 1.獲取Map中的所有鍵

        System.out.println("-------foreach獲取Map中所有的鍵:------");

        Set<String> keys = map.keySet();

        for (String key : keys) {

            System.out.print(key+"  ");

        }

        System.out.println();//換行

        // 2.獲取Map中所有值

        System.out.println("-------foreach獲取Map中所有的值:------");

        Collection<String> values = map.values();

        for (String value : values) {

            System.out.print(value+"  ");

        }

        System.out.println();//換行

        // 3.得到key的值的同時得到key所對應的值

        System.out.println("-------得到key的值的同時得到key所對應的值:-------");

        Set<String> keys2 = map.keySet();

        for (String key : keys2) {

            System.out.print(key + ":" + map.get(key)+"   ");

 

        }

        /**

         * 另外一種不常用的遍歷方式

         */

        // 當我調用put(key,value)方法的時候,首先會把key和value封裝到

        // Entry這個靜態內部類對象中,把Entry對象再添加到數組中,所以我們想獲取

        // map中的所有鍵值對,我們只要獲取數組中的所有Entry對象,接下來

        // 調用Entry對象中的getKey()和getValue()方法就能獲取鍵值對了

        Set<java.util.Map.Entry<String, String>> entrys = map.entrySet();

        for (java.util.Map.Entry<String, String> entry : entrys) {

            System.out.println(entry.getKey() + "--" + entry.getValue());

        }

 

        /**

         * HashMap其他常用方法

         */

        System.out.println("after map.size():"+map.size());

        System.out.println("after map.isEmpty():"+map.isEmpty());

        System.out.println(map.remove("san"));

        System.out.println("after map.remove():"+map);

        System.out.println("after map.get(si):"+map.get("si"));

        System.out.println("after map.containsKey(si):"+map.containsKey("si"));

        System.out.println("after containsValue(李四):"+map.containsValue("李四"));

        System.out.println(map.replace("si""李四2"));

        System.out.println("after map.replace(si, 李四2):"+map);

    }

 

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章