java集合之HashMap源码解读

时间:2024-01-23 06:58:35

源自:jdk1.8.0_121
HashMap继承自AbstractMap,实现了MapCloneableSerializable

HashMap内部是由数组、链表、红黑树实现的

变量

    // 默认大小
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    // 负载因子,默认0.75,当数组
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    static final int TREEIFY_THRESHOLD = 8;

    static final int UNTREEIFY_THRESHOLD = 6;

    static final int MIN_TREEIFY_CAPACITY = 64;

    transient Node<K,V>[] table;

    transient Set<Map.Entry<K,V>> entrySet;

    transient int size;

    transient int modCount;

    int threshold;

    final float loadFactor;
    

构造方法

    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);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

put方法

    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;
        // 如果数组为null或者数组的大小为0时,对数组进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 因为n为2的a次,(2^a - 1) & hash < 2^a,所以不会越界,当tab[i]为空时(索引不冲突),直接插入数组中
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        // 索引冲突时
        else {
            Node<K,V> e; K k;
            // 第一个元素hash和key都冲突时
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 当p为红黑树时
            else if (p instanceof TreeNode)
                // Node转型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);
                        // 当结点数大于等于8
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            // 链表转红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 当hash和key都冲突时,也就是找到了此结点,用于替换
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // hash和key都冲突时,e才会不等于null
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                // 如果onlyIfAbsent为false就不会替换原有的值
                if (!onlyIfAbsent || oldValue == null)
                    // 替换原有的值
                    e.value = value;
                afterNodeAccess(e);
                // 返回被替换的值
                return oldValue;
            }
        }
        ++modCount;
        // 超过最大容量(length * Load factor)时,扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

tableSizeFor方法

    // 返回一个最接近cap的2^n幂
    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;
    }

疑问?

hash % 2^n == hash & (2^n-1)

hash % 2^n 余数是0~2^n-1
hash & (2^n-1) ,也就是取hash的后n位,后n位最大值是2^n-1

当hash = n时

hash n hash % 2^n hash & (2^n-1)
0 0 0 0
1 1 1 1
... ... ... ...
n n n n

当hash = n-a时(hash < n)

hash n hash % 2^n hash & (2^n-1)
0 a 0 0
1 a+1 1 1
... ... ... ...
n-a n n-a n-a

当hash = n+a时(hash > n)

hash n hash % 2^n hash & (2^n-1)
0 -a 0 0
1 -a+1 1 1
... ... ... ...
n+a n n+a n+a

综上所述hash % 2^n == hash & (2^n-1)成立。

Node转型TreeNode(向下转型)

NodeTreeNode都是HashMap的内部类,怎么还能转型的呢?

    // 在HashMap里内部类TreeNode继承了LinkedHashMap的内部类Entry
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>

    // 在LinkedHashMap里内部类Entry又继承了HashMap的内部类Node
    static class Entry<K,V> extends HashMap.Node<K,V>