HashMap源码分析

504 阅读7分钟

1、四种构造方法(重点是前三种)

需要注意的是,所有容量的确定都要推迟到put()方法的时候。无参的容量会变成16,new HashMap(int capacity)和new HashMap(int capacity, int loadFactor)的容量都是大于等于传入的capacity,且是2的某次方的离capacity最近值。(这里要看putVal()和resize()方法)

1.1 无参构造

/**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

其中DEFAULT_LOAD_FACTOR为:

/**
 * The load factor used when none specified in constructor.
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

1.2 只给定capacity的构造方法

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

即加载因子是默认的0.75,但是初始容量是传入的参数initialCapacity,调用下面所述的第三种构造方法

1.3 给定了capacity和threshold的构造方法

/**
 * 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) {
  /*
  总体上说是先判断initialCapacity是否正常,然后判断loadFactor是否合法,最后确定加载因子和门限值
  */
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY) // static final int MAXIMUM_CAPACITY = 1 << 30;
        initialCapacity = MAXIMUM_CAPACITY; // 给的初始容量值太大,超过了2的30次方,则容量只能为2的30次方
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor; // 加载因子的确定
    this.threshold = tableSizeFor(initialCapacity); // 门限值的确定
}

这里的tableSizeFor(int cap)方法,确定了门限值,源码为:

/** 目的就是返回一个比cap大,但是离cap最近的一个2的某次方的值
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1; // 先无符号右移,然后再与运算(无符号右移就是高位补0,低位丢弃。有符号则是高位补最高位,低位照样丢弃)
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

给个小例子:

比方说new HashMap(10, 0.6):
则loadFactor = 0.6f, threshold = 16。
因为按照tableSizeFor()方法,n = 10 - 1 = 9,二进制位1001,然后右移1位,变成0100,此时1001和0100与运算,得到1101。然后接着来,最后n = 1111。返回的则是 n + 1,是十进制的16。但是这个时候,HashMap的数组并没有初始化,只有在put值的时候才会初始化,并且得到初始容量为16(按照这里的门限值确定的,不是因为默认的16),但是刚初始化完数组,数组里全是null,接着hash一个一个地在数组里把key,value组成的节点放进去。(这里因为是第一次,第二次可能会出现在链表或者红黑树的情况,具体看putVal()方法)

1.4 参数传入一个Map的实现类

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

2、hash()方法

源码为:

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

就是一个32位的int型(Object的本地hash()方法得到的一个整数hash),然后将Object的hash值与Object的hash值无符号右移16位后的值异或得到需要确定的hash值。

3、put()方法

源码为:

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

可以看见底层使用的是putVal()方法。

4、putVal()方法

源码为:

    /**
     * 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) {
      // tab是数组, p是节点, n是tab数组的长度
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        
        // 说明只在put元素的时候,HashMap底层tab数组才会resize()初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) // 因为n总是2的某次方,因此(n - 1) & hash等价于 hash % n,但是位运算会比较高效
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k; // 这个时候的p节点是数组上的节点,相同于链表或者红黑树的头节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p; // p此时是数组里的节点,则判断是否相同,相同则更换
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // 倘若p(此时是数组里的节点)是红黑树节点,则按照红黑树插入数据
            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
                          // TREEIFY_THRESHOLD定义为static final int TREEIFY_THRESHOLD = 8;
                            treeifyBin(tab, hash); // treeifyBin方法里,会判断当前数组容量是否小于64,要是小于64的话,则会数组扩容(size*2),否则转换为红黑树。
                        break;
                    }
                  // 如果节点相同,直接退出
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e; // 往后移动链表(与e = p.next呼应)
                }
            }
          
          // 节点相同的情况,则需要替换节点的value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
              // 返回原来的值
                return oldValue;
            }
        }
      // 从 if ((p = tab[i = (n - 1) & hash]) == null) 这里下来的操作,因为那里仅仅是在数组的节点上初始化了一个节点,但是并没有考虑到数组扩容的事情,这里就是判断扩容
        ++modCount; // 这个参数记录了HashMap修改的次数,仅仅在迭代器里用到了,当多线程时:如果一个线程正在迭代,但是另一个线程修改了HashMap,则会报错。因为初始化迭代器的时候,会将modCount的值赋给迭代器的expectModCount。迭代过程中判断modCount和expectModCount是否相等,不相等则说明被修改了报错。
      // ConcurrentModificationException是基于java集合中的快速失败(fail-fast) 机制产生的,在使用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了增删改,就会抛出该异常。 快速失败机制使得java的集合类不能在多线程下并发修改,也不能在迭代过程中被修改。
        if (++size > threshold)
            resize(); // 加入了一个初始化的节点,判断是否需要扩容
        afterNodeInsertion(evict);
        return null;
    }

ps:

为什么重写equals()方法前,一定要重写hashCode()方法?
	因为在实际场景下,很少会用到Object的equals()方法(它是比较二者的引用是否相同),比方说一个学生类,只要两个实例的名字和年龄属性相同,我们就认为相同,此时重写equals()方法,即认为Student a1 = new Student("a", 10); Student a2 = new Student("a", 10)的a1和a2相同。但是如果HashSet则认为二者不同。
	HashSet去重的时候,先比较对象的hashCode(),倘若不一样,直接就认为二者不一样了,此时都不需要去用equals()方法比较。所以要想在实际场景下重写equals()方法,一定要重写hashCode()方法。
	
为什么Java要这么设计equals()和hashCode()呢?
	因为hashCode()方法返回的是一个整型,很容易就能找到。要是两个对象不同,那么它们的hashCode()一定不同,这样比较的话,非常高效。(但是,要是hashCode相同,也不一定说明二者相同)
	
https://www.shouxicto.com/article/2726.html

ps: segmentfault.com/a/119000001…

5、treeifyBin()方法

源码为:

treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) // MIN_TREEIFY_CAPACITY定义为static final int MIN_TREEIFY_CAPACITY = 64;
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

6、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.
     *
     * @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; // 这里比方说你用第三种构造方法构造的HashMap,此时会在这个判断力确定容量是threshold(具体threshold是多少,在第三种构造方法的tableSizeFor()方法里面已经确定过了)
        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;
    }

segmentfault.com/a/119000001…

这是resize()扩容最核心的分裂链表的解析