HashMap 源码解读

HashMap在JDK1.7和1.8中有了很大的改变,空闲时间对HashMap做了一点点的研究。

HashMap是一种数组和链表结合的数据结构,我们每次new一个HashMap时,都会构造出一个长度为16的Entry数组,每一个Entry都是一个单向链表,

网上找的一张图,具体的hashMap的结构如下

Entry的数据结构如图所示

 1 static class Entry<K, V> implements java.util.Map.Entry<K, V> {
 2         final K key;
 3         V value;
 4         HashMap.Entry<K, V> next;
 5         int hash;
 6 
 7         Entry(int arg0, K arg1, V arg2, HashMap.Entry<K, V> arg3) {
 8             this.value = arg2;
 9             this.next = arg3;
10             this.key = arg1;
11             this.hash = arg0;
12         }

 

 

首先先解读JDK1.7的Put方法

 1 public V put(K key, V value) {
 2         if (this.table == EMPTY_TABLE) {
 3             this.inflateTable(this.threshold);
 4         }
 5 
 6         if (key == null) {
 7             return this.putForNullKey(value);
 8         } else {
 9             int hashParam = this.hash(key);
10             int index = indexFor(hashParam, this.table.length);
11 
12             for (HashMap.Entry entry = this.table[index]; entry != null; entry = entry.next) {
13                 if (entry.hash == hashParam) {
14                     Object object = entry.key;
15                     if (entry.key == key || key.equals(object)) {
16                         Object arg6 = entry.value;
17                         entry.value = value;
18                         entry.recordAccess(this);
19                         return arg6;
20                     }
21                 }
22             }
23 
24             ++this.modCount;
25             this.addEntry(hashParam, key, value, index);
26             return null;
27         }
28     }

2-4行:如果table还未初始化,则先进行初始化

6-7行:如果key的值为空,则把把value值放到第一个位置,具体的代码如下

1 private V putForNullKey(V value) {
2         for (HashMap.Entry entry = this.table[0]; entry != null; entry = entry.next) {
3             if (entry.key == null) {
4                 Object object = entry.value;
5                 entry.value = value;
6                 entry.recordAccess(this);
7                 return object;
8             }
9         }

9行:根据重新计算的HashCode,对Entry数组的大小取模得到一个Entry数组的位置。注意HashMap构造函数中,如果你指定HashMap初始数组的大小initialCapacity,如果initialCapacity不是2的N次幂,HashMap会算出大于initialCapacity的最小2的N次幂的值,作为Entry数组的初始化大小

10行:根据上一步的hashcode值,以及数组的长度,确定出该key所处的下标值

12-19行:首先会判断这个数组里面所有的元素是的hash是否一样,如果hash一样,那么再去判断key值是否一样,如果key值也一样,则会覆盖原先key的value

24-26:如果都不一样,则会在当前的数组中,插入一个链表

 

移除元素

 1 public V remove(Object oldKey) {
 2         HashMap.Entry entry = this.removeEntryForKey(oldKey);
 3         return entry == null ? null : entry.value;
 4     }
 5 
 6     final HashMap.Entry<K, V> removeEntryForKey(Object oldKey) {
 7         if (this.size == 0) {
 8             return null;
 9         } else {
10             int hashCode = oldKey == null ? 0 : this.hash(oldKey);
11             int index = indexFor(hashCode, this.table.length);
12             HashMap.Entry entry1 = this.table[index];
13 
14             HashMap.Entry entry2;
15             HashMap.Entry entry3;
16             for (entry2 = entry1; entry2 != null; entry2 = entry3) {
17                 entry3 = entry2.next;
18                 if (entry2.hash == hashCode) {
19                     Object arg6 = entry2.key;
20                     if (entry2.key == oldKey || oldKey != null && oldKey.equals(arg6)) {
21                         ++this.modCount;
22                         --this.size;
23                         if (entry1 == entry2) {
24                             this.table[index] = entry3;
25                         } else {
26                             entry1.next = entry3;
27                         }
28 
29                         entry2.recordRemoval(this);
30                         return entry2;
31                     }
32                 }
33 
34                 entry1 = entry2;
35             }
36 
37             return entry2;
38         }
39     }

移除元素的操作也很简单

7-8行判断元素是否为空,为空直接返回NULL

10-12行 的操作和put一样,获得key的hash值,然后根据hash值和table数组的大小取模,获得值便是key所处于这个数组的下标,当我们确定是哪个entry时,我们就可以进入到entry链表内部

16-27行 链表从头开始向后寻找,直到找到hashcode的值和key的值都一样的,把上一个链表的next指向下一个链表,这样就把当前的节点给剔除了

 JDK8


 

//final修饰 方法内联
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为空,调用resize初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //根据hash获取下标i,如果tab[i]的node为空,调用newNode新建一个node
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //如果tab[i]的node为不为空,即存在node链表
            Node<K,V> e; K k;
            //先判断第一个Node的key是否相同,是的话结束判断得到e,
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //调用btree的putTreeVal
            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; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } //map的putval可以看成getAndSet if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }

 

posted @ 2017-06-15 17:42  XuMinzhe  阅读(270)  评论(0编辑  收藏  举报