Java HashMap 源码分析

HashMap实现简介

HashMap 底层采用节点数组,数组内存储的是链表或者红黑树(JDK8)

1. 源码分析

1.1 属性

/**
     * The default initial capacity - MUST be a power of two.
     * 默认容量必须是2的倍数    这里是16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     * 这里是2的30次方,int正数的大小最大是2的31次方 
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * 装载系数, 最大容量=容量*装载系数
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     *
     * 链表的最大长度是8,当超过这个长度时转换成树
     *
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     *
      *当执行resize操作时,当容器中bin的数量少于UNTREEIFY_THRESHOLD时使用链表来代替树。默认值是6
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     *
     * 当桶中的bin被树化时最小的hash表容量。(如果没有达到这个阈值,即hash表容量小于
     * MIN_TREEIFY_* CAPACITY,当桶中bin的数量太多时会执行resize扩容操作)
     * 这个MIN_TREEIFY_CAPACITY的值至少是TREEIFY_THRESHOLD的4倍
     */
    static final int MIN_TREEIFY_CAPACITY = 64;


    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     * 节点数组
     */
    transient Node<K,V>[] table;

1.2 链表节点实现

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;  //hash值
        final K key;     //key值
        V value;         //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; }

        /**
         * 获取节点的hash值,key、value的hash值求异或
         *
         **/
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        //节点key,vaule值都相等,节点才相等
        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.3 构造函数

/**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public 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);
    }

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

tableSizeFor的功能:
调用 int result = tableSizeFor(18);
- int n = cap -1;
n = 17 二进制 n = 10001
- n |= n >>> 1;

10001       n
 |  01000       n >>> 1
---------------
    11001
  • n |= n >>> 2;
11001       n
 |  00110       n >>> 2
---------------
    11111
  • n |= n >>> 4;
11111       n
 |  00001       n >>> 4
---------------
    11111
  • n |= n >>> 4;
11111       n
 |  00000       n >>> 16
---------------
    11111       n = 31

java int占有4个字节32位,上述计算n总共无符号右移32位 n+1 = 32

由上分析tableSizeFor(int cap)方法返回大于等于cap的最小2的幂值

tableSizeFor(31) –> 32

tableSizeFor(33) –> 64

1.4 put方法

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

   /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     *
     * key值的hash值与hash值右移16位求异或,作为key的hash值
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
     /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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)
            //tab为空,调整table的大小
            n = (tab = resize()).length;
        //tab索引的计算方式 tab的大小与hash求与
        if ((p = tab[i = (n - 1) & hash]) == null)
            //当前index位置不存在元素,新分配节点
            tab[i] = newNode(hash, key, value, null);
        else {
        //index位置已存在节点
            Node<K,V> e; K k;
            //index位置已存在首节点的hash值与put进来的hash值一样
            //并且节点key值与新节点key值相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //index已存在首节点,且是TreeNode类型,树容器put
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //其他,普通情况
            else {
                for (int binCount = 0; ; ++binCount) {
                    //新put的节点链接到数组索引处链表的最后一个位置
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //链表长度超出转换为树结构的阙值,树型转换
                            treeifyBin(tab, hash);
                        break;
                    }
                    //index处的链表某节点与put的新节点相同
                    //节点hash相同,key相同或值相等
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //value赋值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //table元素大小超过阙值,重新分配大小
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

1.4.1 hash表的存储方式

Node

graph LR
A-->A1
A1-->A2
A2-->A3
B-->B1
B1-->B2
B2-->B3
C-->C1
C1-->C2
C2-->C3

1.4.2 key 的索引计算方式

index = (tables.length - 1) & [(hash = key.hashCode()) ^ (hash >>> 16)]
tables的大小只能是2的幂 16,32,64 …..
tables.length -1 的二进制数也就是全1, 1111,11111,111111
其与任何二进制数求与得到index值,则index都会小于tables.length

1.4.3 散列表冲突解决

  1. 链接方法
    hashMap采用链表的方式解决hash冲突
    当hash函数求得的index与已经存在的rootNode相同时,如果key也相同则覆盖其value值,key值不相同的话进行此index处的链表遍历,其中发现key值存在的话进行覆盖,不存在的话新node附加到链表尾部
  2. 开放寻址法
    开放寻址发,所有的元素都被散列到表中,也就是说,每个表项或包含动态集合中的一个元素,或包含NIL,当查找某个元素时候,要系统的检查所有的表项,直到查到所需元素,或元素不在表中

1.5 resize重新分配大小

/**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     * 重新分配table大小,原大小的二倍
     * @return the table
     */
    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;
            }
            //数组大小没有大于最大值
            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 {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        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) {
            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 { // 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 {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

*
index的计算方式hash & (cap -1)此处为什么是 (e.hash & oldCap) == 0

假设oldCap=16,oldindex = e.hash & 15

e.hash
  & 00001111     15
-------------------
    0000xxxx    后四位决定索引的值

现在进行扩容 newCap = 32,newIndex = e.hash & 31

e.hash
  & 000011111    31
-------------------
    0000yxxxx 后五位决定新索引的值,且第五位决定index是否变动为oldCap+index

看下e.hash & oldCap的结果:

e.hash
  & 000010000    16
-------------------
    0000y0000

如果e.hash的后数第五位是0那么结果就是y=0那么节点新索引就没有变化,也就有了上面后面的代码,将索引需要变化的节点组成新的链表,链接到newTable的oldCap+j位置,索引不需要变化的重新组成链表放到原索引处

1.6 红黑树部分

当链表的长度大于阙值时,链表会被转换为红黑树,
链表的搜索、插入等操作时间复杂度O(n),红黑树为平衡二叉树其为lg(n)(最坏情况下也是)