Java HashMap源码分析(转)

Java HashMap源码分析

ImportNew 昨天

(给ImportNew加星标,提高Java技能)

 

转自:Snailclimb

文章链接:https://github.com/Snailclimb/JavaGuide/blob/master/Java%E7%9B%B8%E5%85%B3/HashMap.md

 

本文从 Hash 方法开始,通过分析源码,深入介绍了 JDK 不同版本中 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 方法更加简化,但是原理不变。

 

 

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 方法源码。

 

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 次。

 

所谓 “拉链法” 就是:将链表和数组相结合。也就是说创建一个链表数组,数组中每一格就是一个链表。若遇到哈希冲突,则将冲突的值加到链表中即可。

 

 

JDK1.8之后

 

相比于之前的版本,JDK 1.8在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。

 

 

类的属性

 

 1 public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
 2     // 序列号
 3     private static final long serialVersionUID = 362498820763181265L;    
 4     // 默认的初始容量是16
 5     static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   
 6     // 最大容量
 7     static final int MAXIMUM_CAPACITY = 1 << 30; 
 8     // 默认的填充因子
 9     static final float DEFAULT_LOAD_FACTOR = 0.75f;
10     // 当桶(bucket)上的结点数大于这个值时会转成红黑树
11     static final int TREEIFY_THRESHOLD = 8; 
12     // 当桶(bucket)上的结点数小于这个值时树转链表
13     static final int UNTREEIFY_THRESHOLD = 6;
14     // 桶中结构转化为红黑树对应的table的最小大小
15     static final int MIN_TREEIFY_CAPACITY = 64;
16     // 存储元素的数组,总是2的幂次倍
17     transient Node<k,v>[] table; 
18     // 存放具体元素的集
19     transient Set<map.entry<k,v>> entrySet;
20     // 存放元素的个数,注意这个不等于数组的长度。
21     transient int size;
22     // 每次扩容和更改map结构的计数器
23     transient int modCount;   
24     // 临界值 当实际大小(容量*填充因子)超过临界值时,会进行扩容
25     int threshold;
26     // 填充因子
27     final float loadFactor;
28 }

 

loadFactor加载因子

 

loadFactor加载因子是控制数组存放数据的疏密程度,loadFactor越趋近于1,那么 数组中存放的数据(entry)也就越多,也就越密,也就是会让链表的长度增加,load Factor越小,也就是趋近于0。

 

loadFactor太大导致查找元素效率低,太小导致数组的利用率低,存放的数据会很分散。loadFactor的默认值为0.75f是官方给出的一个比较好的临界值。

 

threshold

 

threshold = capacity * loadFactor,当Size>=threshold的时候,那么就要考虑对数组的扩增了,也就是说,这个的意思就是 衡量数组是否需要扩增的一个标准。

 

Node节点类源码

 

 1 // 继承自 Map.Entry<K,V>
 2 static class Node<K,V> implements Map.Entry<K,V> {
 3        final int hash;// 哈希值,存放元素到hashmap中时用来与其他元素hash值比较
 4        final K key;//
 5        V value;// 6        // 指向下一个节点
 7        Node<K,V> next;
 8        Node(int hash, K key, V value, Node<K,V> next) {
 9             this.hash = hash;
10             this.key = key;
11             this.value = value;
12             this.next = next;
13         }
14         public final K getKey()        { return key; }
15         public final V getValue()      { return value; }
16         public final String toString() { return key + "=" + value; }
17         // 重写hashCode()方法
18         public final int hashCode() {
19             return Objects.hashCode(key) ^ Objects.hashCode(value);
20         }
21  
22         public final V setValue(V newValue) {
23             V oldValue = value;
24             value = newValue;
25             return oldValue;
26         }
27         // 重写 equals() 方法
28         public final boolean equals(Object o) {
29             if (o == this)
30                 return true;
31             if (o instanceof Map.Entry) {
32                 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
33                 if (Objects.equals(key, e.getKey()) &&
34                     Objects.equals(value, e.getValue()))
35                     return true;
36             }
37             return false;
38         }
39 }

 

 

树节点类源码

 

 1 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
 2         TreeNode<K,V> parent;  //
 3         TreeNode<K,V> left;    //
 4         TreeNode<K,V> right;   //
 5         TreeNode<K,V> prev;    // needed to unlink next upon deletion
 6         boolean red;           // 判断颜色
 7         TreeNode(int hash, K key, V val, Node<K,V> next) {
 8             super(hash, key, val, next);
 9         }
10         // 返回根节点
11         final TreeNode<K,V> root() {
12             for (TreeNode<K,V> r = this, p;;) {
13                 if ((p = r.parent) == null)
14                     return r;
15                 r = p;
16        }

 

 

HashMap源码分析

 

构造方法

 

 

 1 // 默认构造函数。
 2 public More ...HashMap() {
 3     this.loadFactor = DEFAULT_LOAD_FACTOR; // all   other fields defaulted
 4  }
 5  
 6  // 包含另一个“Map”的构造函数
 7  public More ...HashMap(Map<? extends K, ? extends V> m) {
 8      this.loadFactor = DEFAULT_LOAD_FACTOR;
 9      putMapEntries(m, false);//下面会分析到这个方法
10  }
11  
12  // 指定“容量大小”的构造函数
13  public More ...HashMap(int initialCapacity) {
14      this(initialCapacity, DEFAULT_LOAD_FACTOR);
15  }
16  
17  // 指定“容量大小”和“加载因子”的构造函数
18  public More ...HashMap(int initialCapacity, float loadFactor) {
19      if (initialCapacity < 0)
20          throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
21      if (initialCapacity > MAXIMUM_CAPACITY)
22          initialCapacity = MAXIMUM_CAPACITY;
23      if (loadFactor <= 0 || Float.isNaN(loadFactor))
24          throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
25      this.loadFactor = loadFactor;
26      this.threshold = tableSizeFor(initialCapacity);
27  }

 

 

putMapEntries方法

 

 1 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
 2     int s = m.size();
 3     if (s > 0) {
 4         // 判断table是否已经初始化
 5         if (table == null) { // pre-size
 6             // 未初始化,s为m的实际元素个数
 7             float ft = ((float)s / loadFactor) + 1.0F;
 8             int t = ((ft < (float)MAXIMUM_CAPACITY) ?
 9                     (int)ft : MAXIMUM_CAPACITY);
10             // 计算得到的t大于阈值,则初始化阈值
11             if (t > threshold)
12                 threshold = tableSizeFor(t);
13         }
14         // 已初始化,并且m元素个数大于阈值,进行扩容处理
15         else if (s > threshold)
16             resize();
17         // 将m中的所有元素添加至HashMap中
18         for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
19             K key = e.getKey();
20             V value = e.getValue();
21             putVal(hash(key), key, value, false, evict);
22         }
23     }
24 }

 

 

put方法

 

HashMap只提供了put用于添加元素,putVal方法只是给put方法调用的一个方法,并没有提供给用户使用。

 

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

 

  • 如果定位到的数组位置没有元素就直接插入。

  • 如果定位到的数组位置有元素就和要插入的 key 比较,如果key相同就直接覆盖,如果 key 不相同,就判断 p 是否是一个树节点,如果是就调用 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value) 将元素添加进入。如果不是就遍历链表插入。

 

 

 1 public V put(K key, V value) {
 2     return putVal(hash(key), key, value, false, true);
 3 }
 4  
 5 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
 6                    boolean evict) {
 7     Node<K,V>[] tab; Node<K,V> p; int n, i;
 8     // table未初始化或者长度为0,进行扩容
 9     if ((tab = table) == null || (n = tab.length) == 0)
10         n = (tab = resize()).length;
11     // (n - 1) & hash 确定元素存放在哪个桶中,桶为空,新生成结点放入桶中(此时,这个结点是放在数组中)
12     if ((p = tab[i = (n - 1) & hash]) == null)
13         tab[i] = newNode(hash, key, value, null);
14     // 桶中已经存在元素
15     else {
16         Node<K,V> e; K k;
17         // 比较桶中第一个元素(数组中的结点)的hash值相等,key相等
18         if (p.hash == hash &&
19             ((k = p.key) == key || (key != null && key.equals(k))))
20                 // 将第一个元素赋值给e,用e来记录
21                 e = p;
22         // hash值不相等,即key不相等;为红黑树结点
23         else if (p instanceof TreeNode)
24             // 放入树中
25             e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
26         // 为链表结点
27         else {
28             // 在链表最末插入结点
29             for (int binCount = 0; ; ++binCount) {
30                 // 到达链表的尾部
31                 if ((e = p.next) == null) {
32                     // 在尾部插入新结点
33                     p.next = newNode(hash, key, value, null);
34                     // 结点数量达到阈值,转化为红黑树
35                     if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
36                         treeifyBin(tab, hash);
37                     // 跳出循环
38                     break;
39                 }
40                 // 判断链表中结点的key值与插入的元素的key值是否相等
41                 if (e.hash == hash &&
42                     ((k = e.key) == key || (key != null && key.equals(k))))
43                     // 相等,跳出循环
44                     break;
45                 // 用于遍历桶中的链表,与前面的e = p.next组合,可以遍历链表
46                 p = e;
47             }
48         }
49         // 表示在桶中找到key值、hash值与插入元素相等的结点
50         if (e != null) { 
51             // 记录e的value
52             V oldValue = e.value;
53             // onlyIfAbsent为false或者旧值为null
54             if (!onlyIfAbsent || oldValue == null)
55                 //用新值替换旧值
56                 e.value = value;
57             // 访问后回调
58             afterNodeAccess(e);
59             // 返回旧值
60             return oldValue;
61         }
62     }
63     // 结构性修改
64     ++modCount;
65     // 实际大小大于阈值则扩容
66     if (++size > threshold)
67         resize();
68     // 插入后回调
69     afterNodeInsertion(evict);
70     return null;
71 }

 

 

我们再来对比一下 JDK1.7 put方法的代码

 

对于put方法的分析如下:

 

  • 如果定位到的数组位置没有元素就直接插入。

  • 如果定位到的数组位置有元素,遍历以这个元素为头结点的链表,依次和插入的key比较,如果key相同就直接覆盖,不同就采用头插法插入元素。

 

 1 public V put(K key, V value)
 2     if (table == EMPTY_TABLE) { 
 3     inflateTable(threshold); 
 4 }  
 5     if (key == null)
 6         return putForNullKey(value);
 7     int hash = hash(key);
 8     int i = indexFor(hash, table.length);
 9     for (Entry<K,V> e = table[i]; e != null; e = e.next) { // 先遍历
10         Object k;
11         if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
12             V oldValue = e.value;
13             e.value = value;
14             e.recordAccess(this);
15             return oldValue; 
16         }
17     }
18  
19     modCount++;
20     addEntry(hash, key, value, i);  // 再插入
21     return null;
22 }

 

 

get方法

 

 1 public V get(Object key) {
 2     Node<K,V> e;
 3     return (e = getNode(hash(key), key)) == null ? null : e.value;
 4 }
 5  
 6 final Node<K,V> getNode(int hash, Object key) {
 7     Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
 8     if ((tab = table) != null && (n = tab.length) > 0 &&
 9         (first = tab[(n - 1) & hash]) != null) {
10         // 数组元素相等
11         if (first.hash == hash && // always check first node
12             ((k = first.key) == key || (key != null && key.equals(k))))
13             return first;
14         // 桶中不止一个节点
15         if ((e = first.next) != null) {
16             // 在树中get
17             if (first instanceof TreeNode)
18                 return ((TreeNode<K,V>)first).getTreeNode(hash, key);
19             // 在链表中get
20             do {
21                 if (e.hash == hash &&
22                     ((k = e.key) == key || (key != null && key.equals(k))))
23                     return e;
24             } while ((e = e.next) != null);
25         }
26     }
27     return null;
28 }

 

 

resize方法

 

进行扩容,会伴随着一次重新hash分配,并且会遍历hash表中所有的元素,是非常耗时的。在编写程序中,要尽量避免resize。

 

 1 final Node<K,V>[] resize() {
 2     Node<K,V>[] oldTab = table;
 3     int oldCap = (oldTab == null) ? 0 : oldTab.length;
 4     int oldThr = threshold;
 5     int newCap, newThr = 0;
 6     if (oldCap > 0) {
 7         // 超过最大值就不再扩充了,就只好随你碰撞去吧
 8         if (oldCap >= MAXIMUM_CAPACITY) {
 9             threshold = Integer.MAX_VALUE;
10             return oldTab;
11         }
12         // 没超过最大值,就扩充为原来的2倍
13         else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
14             newThr = oldThr << 1; // double threshold
15     }
16     else if (oldThr > 0) // initial capacity was placed in threshold
17         newCap = oldThr;
18     else { 
19         signifies using defaults
20         newCap = DEFAULT_INITIAL_CAPACITY;
21         newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
22     }
23     // 计算新的resize上限
24     if (newThr == 0) {
25         float ft = (float)newCap * loadFactor;
26         newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE);
27     }
28     threshold = newThr;
29     @SuppressWarnings({"rawtypes","unchecked"})
30         Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
31     table = newTab;
32     if (oldTab != null) {
33         // 把每个bucket都移动到新的buckets中
34         for (int j = 0; j < oldCap; ++j) {
35             Node<K,V> e;
36             if ((e = oldTab[j]) != null) {
37                 oldTab[j] = null;
38                 if (e.next == null)
39                     newTab[e.hash & (newCap - 1)] = e;
40                 else if (e instanceof TreeNode)
41                     ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
42                 else { 
43                     Node<K,V> loHead = null, loTail = null;
44                     Node<K,V> hiHead = null, hiTail = null;
45                     Node<K,V> next;
46                     do {
47                         next = e.next;
48                         // 原索引
49                         if ((e.hash & oldCap) == 0) {
50                             if (loTail == null)
51                                 loHead = e;
52                             else
53                                 loTail.next = e;
54                             loTail = e;
55                         }
56                         // 原索引+oldCap
57                         else {
58                             if (hiTail == null)
59                                 hiHead = e;
60                             else
61                                 hiTail.next = e;
62                             hiTail = e;
63                         }
64                     } while ((e = next) != null);
65                     // 原索引放到bucket里
66                     if (loTail != null) {
67                         loTail.next = null;
68                         newTab[j] = loHead;
69                     }
70                     // 原索引+oldCap放到bucket里
71                     if (hiTail != null) {
72                         hiTail.next = null;
73                         newTab[j + oldCap] = hiHead;
74                     }
75                 }
76             }
77         }
78     }
79     return newTab;
80 }

 

 

HashMap常用方法测试


 1 package map;
 2  
 3 import java.util.Collection;
 4 import java.util.HashMap;
 5 import java.util.Set;
 6  
 7 public class HashMapDemo {
 8  
 9     public static void main(String[] args) {
10         HashMap<String, String> map = new HashMap<String, String>();
11         // 键不能重复,值可以重复
12         map.put("san", "张三");
13         map.put("si", "李四");
14         map.put("wu", "王五");
15         map.put("wang", "老王");
16         map.put("wang", "老王2");// 老王被覆盖
17         map.put("lao", "老王");
18         System.out.println("-------直接输出hashmap:-------");
19         System.out.println(map);
20         /**
21          * 遍历HashMap
22          */
23         // 1.获取Map中的所有键
24         System.out.println("-------foreach获取Map中所有的键:------");
25         Set<String> keys = map.keySet();
26         for (String key : keys) {
27             System.out.print(key+"  ");
28         }
29         System.out.println();//换行
30         // 2.获取Map中所有值
31         System.out.println("-------foreach获取Map中所有的值:------");
32         Collection<String> values = map.values();
33         for (String value : values) {
34             System.out.print(value+"  ");
35         }
36         System.out.println();//换行
37         // 3.得到key的值的同时得到key所对应的值
38         System.out.println("-------得到key的值的同时得到key所对应的值:-------");
39         Set<String> keys2 = map.keySet();
40         for (String key : keys2) {
41             System.out.print(key + ":" + map.get(key)+"   ");
42  
43         }
44         /**
45          * 另外一种不常用的遍历方式
46          */
47         // 当我调用put(key,value)方法的时候,首先会把key和value封装到
48         // Entry这个静态内部类对象中,把Entry对象再添加到数组中,所以我们想获取
49         // map中的所有键值对,我们只要获取数组中的所有Entry对象,接下来
50         // 调用Entry对象中的getKey()和getValue()方法就能获取键值对了
51         Set<java.util.Map.Entry<String, String>> entrys = map.entrySet();
52         for (java.util.Map.Entry<String, String> entry : entrys) {
53             System.out.println(entry.getKey() + "--" + entry.getValue());
54         }
55  
56         /**
57          * HashMap其他常用方法
58          */
59         System.out.println("after map.size():"+map.size());
60         System.out.println("after map.isEmpty():"+map.isEmpty());
61         System.out.println(map.remove("san"));
62         System.out.println("after map.remove():"+map);
63         System.out.println("after map.get(si):"+map.get("si"));
64         System.out.println("after map.containsKey(si):"+map.containsKey("si"));
65         System.out.println("after containsValue(李四):"+map.containsValue("李四"));
66         System.out.println(map.replace("si", "李四2"));
67         System.out.println("after map.replace(si, 李四2):"+map);
68     }
69  
70 }

 

 

看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

posted @ 2019-01-08 18:26  William_R  阅读(73)  评论(0)    收藏  举报