HashMap源码解析

更新时间:2016-12-07 10:22:51 点击次数:1946次

在 Java8 之前, HashMap 是链表散列的数据结构,即数组和链表的结合体;从 Java8 开始,引入红黑树的数据结构和扩容的优化。

分析版本: JDK1.8

Node

从 Java8 引入红黑树之后, HashMap 是由数组、链表和红黑树组成,发现源码有些地方与之前不同,那就是 Node :

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { static class Node<K,V> implements Map.Entry<K,V> { final int 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; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value);
        } public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue; return oldValue;
        } 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;
        }
    }
}

Node ,也就是以前的 Entry ,内容没变,只是换了一种叫法。

put(K key, V value)

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { transient Node<K,V>[] table; public V put(K key, V value) { return putVal(hash(key), key, value, false, true);
    } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null); else {
            Node<K,V> e; K k; if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p; 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;
                }
            } 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;
    } static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    } final Node<K,V>[] resize() {
        ....
    } Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next);
    } static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        ....
    } final void treeifyBin(Node<K,V>[] tab, int hash) {
        ....
    } void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { }

}

HashMap 使用哈希表来存储。哈希表为解决冲突,可以采用开放地址法和链地址法等来解决问题,Java 中 HashMap 采用了链地址法。链地址法,就是数组加链表的结合。在每个数组元素上都一个链表结构,当数据被Hash后,得到数组下标,把数据放在对应下标元素的链表上。

当我们往 HashMap 中 put 元素的时候,先根据 key 的 hashCode 重新计算 hash 值,根据 hash 值再通过高位运算和取模运算得到这个元素在数组中的位置(即下标),如果数组该位置上已经存放有其他元素了,那么在这个位置上的元素将以链表的形式存放,新加入的放在链头,先加入的放在链尾,如果该链表超出 8 个的话,就转换成红黑树。如果数组该位置上没有元素,就直接将该元素放到此数组中的该位置上。

hash(Object key)

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { int n, i; if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null)//取模运算 tab[i] = newNode(hash, key, value, null); else {
        ....
	} static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//取hashCode值和高位参与运算 }
     
}

定位位置的方法通过以上三个步骤得到,取 key 的 hashCode 的值,然后进行无符号右移 16 位,再与现有哈希桶数组的大小取模。通过 (n - 1) & hash 来得到该对象的保存位求得这个位置的时候,马上就可以知道对应位置的元素,不用遍历链表,大大优化了查询的效率。

当 length 总是 2 的 n 次方时,(length - 1) & hash 运算等价于对 length 取模,也就是h % length,但是 & 比 % 具有更高的效率。

注意,在 Java8 之前的算法是这样的:

static int hash(int h) {  
    h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);  
} static int indexFor(int hash, int length) { return hash & (length-1);
}

Java8 优化了高位运算的算法,通过 hashCode() 的高 16 位异或低 16 位实现的:(h = k.hashCode()) ^ (h >>> 16),主要是从速度、功效、质量来考虑的,这么做可以在数组 table 的 length 比较小的时候,也能保证考虑到高低 Bit 都参与到 Hash 的计算中,同时不会有太大的开销。

putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { transient Node<K,V>[] table; final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0)//如果为null或者大小为0则创建 n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null)//计算index tab[i] = newNode(hash, key, value, null); else {
            Node<K,V> e; K k; if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//如果有key,那么直接覆盖value e = p; 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);//链表长度大于8转换为红黑树进行处理 break;
                    } if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) break;
                    p = e;//key已经存在直接覆盖value }
            } 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;
    }
}
  1. 当 table 数组为 null 或者大小为 0 的时候进行扩容。
  2. 第二步,计算出该 key 的索引 index 。
  3. 找到 table 数组中该位置,判断该位置上是否有值:
    1. 如果有,判断 key 的 hashCode() 和 equals() 是否相等,相等的话覆盖,不相等的话再判断是否是红黑树还是链表。
    2. 如果没有,判断是不是红黑树:
      1. 是,就插入到红黑树中;
      2. 不是话,遍历链表,如果大小大于8,转换成红黑树,插入到红黑树中,不大于8的话就插入到链表,如果在遍历的是否发现hashCode() 和 equals() 相等。
  4. 插入成功后,判断 table 数组大小是否超过了大容量,是的话扩容

resize()

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { static final int MAXIMUM_CAPACITY = 1 << 30; static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 static final float DEFAULT_LOAD_FACTOR = 0.75f; 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) {//扩容前的旧的数组大小如果已经达到大(2^30) threshold = Integer.MAX_VALUE;////修改大容量为int的大值(2^31-1),这样以后就不会扩容了 return oldTab;
            } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)//扩容后的小于数组大小大值 newThr = oldThr << 1; // double threshold 在旧值上乘以2 } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr;//旧的大容量就是新的数组容量 else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY;//16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//0.75*16 } 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;//新的table数组 if (oldTab != null) { 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;//给e找位置 else if (e instanceof TreeNode)//如果是红黑树 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order 处理链表 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;
                            } else {//原来的索引+oldCap if (hiTail == null)
                                    hiHead = e; else hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null); if (loTail != null) {//原索引放到新table数组里 loTail.next = null;
                            newTab[j] = loHead;
                        } if (hiTail != null) {//原索引+oldCap放到新table数组里 hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        } return newTab;
    }
}

本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是一个个人学习交流的平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽,造成漏登,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

回到顶部
嘿,我来帮您!