Java集合源码分析(五)——HashMap

简介

HashMap 是一个散列表,存储的内容是键值对映射。
HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
HashMap 存储的键值对是无序的。

源码分析

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {}

实现接口

  • Map
  • Cloneable
  • Serializable

父类

  • AbstractMap

字段

	// 默认初始容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
	// 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
	// 默认的加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
	// 树化阈值
    static final int TREEIFY_THRESHOLD = 8;
	// 树退化阈值
    static final int UNTREEIFY_THRESHOLD = 6;
	// 最小树化容量,也就是Node数组大小要达到这个值了之后,才可能有树产生
    static final int MIN_TREEIFY_CAPACITY = 64;

	// 存储数据的Node数组
    transient Node<K,V>[] table;
    // 键值对的集合
    transient Set<Map.Entry<K,V>> entrySet;
    // HashMap中键值对的数量
    transient int size;
    // 被修改的次数
    transient int modCount;
	// 阈值,用于判断是否需要调整容量
    int threshold;
    // 加载因子
    final float loadFactor;

内部类

1.键值对结构

    // HashMap的键值对节点结构,实现了Map.Entry的接口
    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;
        }
    }

这里的Objects.equals()函数比较的实现原理是什么样的?
Objects.equals()源码返回的是return (a == b) || (a != null && a.equals(b));可以看出,先比较二者的引用是否相等,如果不相等,就调用对象内重写的逻辑equals函数进行对比。

2.树节点结构

    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

		// 省略内部方法若干
    }

太长了,还是重新开一篇写吧。

方法

1.构造函数

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

提供了四种初始化的方法,可以自由定义Map的初始容量和加载因子,或者从其他Map中获取数据。

2.哈希函数

    static final int hash(Object key) {
        int h;
        // 计算哈希值,null的哈希值就是0
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

为什么这里的哈希值运算是这样的呢?(h = key.hashCode()) ^ (h >>> 16)

由于下面用哈希值和列表长度(length-1)进行一个位与运算,以此获得对应的槽的位置,但是length 绝大多数情况小于2的16次方。所以始终是hashcode的低16位(甚至更低)参与运算。要是高16位也参与运算,会让得到的下标更加散列。
所以这样高16位是用不到的,如何让高16也参与运算呢。所以才有hash(Object key)方法。让他的hashCode()和自己的高16位^运算。所以(h >>> 16)得到他的高16位与hashCode()进行^运算。
同时用^可以更加平均1和0。
参考博客

3.查找元素

	// 对外部的获取键值的接口函数
    public V get(Object key) {
        Node<K,V> e;
        // 通过获取内部节点提取节点值,如果没有就返回null
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
    // 是否存在键
    public boolean containsKey(Object key) {
    	// 原理同上
        return getNode(hash(key), key) != null;
    }
    
	// 根据哈希值获取对应节点
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 判断表中是否有数据      (n - 1) & hash == hash % n
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 判断第一个节点是否就是想要找的,因为大多数时候一个位置只有一个值
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 判断下一个节点是不是空的
            if ((e = first.next) != null) {
            	// 判断是不是已经进化为树了
                if (first instanceof TreeNode)
                	// 查询树
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 遍历链表
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

节点查找的思路很清晰:

  1. 判断表是否为空,不是就找到对应的槽;
  2. 判断哈希映射的槽是否为空,不是就获取其头节点;
  3. 判断第一个值是不是目标,不是就以第一个节点开始,查询树或者是链表。

为什么(n - 1) & hash == hash % n?
参考博客

其中instanceof用于判断前者对象是否为后者类的一个实例。

如果发现头节点已经是一棵树,那么就调用树的查找函数进行元素查找。

4.表扩容

    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 { 
            // 如果上面二者都是0,则是第一次扩容,全部设置为初始值
            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 { 
                    	// 节点是链表,那就需要把链表中的数组再拆散成两个,再分别放到对应的位置上
                    	// 低位的头节点
                        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;
    }

扩容条件:如果现有容量值没有超出范围,则可以调用这个方法进行一次扩容。

扩容大小: 除了第一次扩容是扩到默认值16,后来的每次扩容都是原来的两倍。扩容阈值就是新容量和加载因子之积,所以也是原来的两倍。

如何将旧表中的数据复制到新表中呢?

  • 如果原有节点是树,则进行一次树的拆分操作。
  • 如果原有节点是链表,则根据(e.hash & oldCap) == 0条件拆分链表,然后放到新表中的对应位置。

(e.hash & oldCap) == 0条件是怎么来的呢?
就是需要判断新表的大小和节点哈希值去余是否会发生变化,因为新表的尺寸是原表的两倍,那么如果hash值小于原表的尺寸,那么新表的尺寸和这个哈希值取余的值还是一样的,所以,就直接放在旧的位置即可。

参考博客

5.修改添加元素

	// 根据键修改或者添加值
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

	// 根据哈希值,修改或者添加原表,其中参数onlyIfAbsent如果是true,就不会修改原有值
	// 如果evict为false,则表就是处于创建模式
    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) {
                    	// 不存在key的节点,所以需要新建一个节点
                        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) { 
            	// 存在当前的键值,那就直接修改键存储的值
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 为LinkedHashMap留后路,为了实现顺序存储
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
        	// 最后进行扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }

添加值时的思路:

  1. 如果表中不存在需要添加的键值,则新建节点添加,如果对应槽位是树,则直接将节点插入到树中,如果当前槽位是链表,就先加到链表末尾,然后判断链表长度是否超出了树化的长度,超了就将链表树化。
  2. 如果表中存在需要添加的键值,则查询到原来的节点,树或者链表,然后直接修改节点上的值。
  3. 与List不同的是,Map是先加入节点,再判断扩容,而List是先判断是不是需要扩容,再加入节点。

6.树化对应链表

	// 这里只是进行一个初步的判断链表是不是需要树化,和将原来的链表构造位新的双向链表
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        	// 如果只是因为数组太小导致单个槽位的节点过多,那就进行一次扩容
            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);
        }
    }

7.删除元素

	// 删除对应键的键值对
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
	// 根据节点的hash值删除节点
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        // 判断节点是否存在
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            // 获取到头节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            // 头节点不是想要的,那就向下查找,同样分别是找树或者链表
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            // 找到了想要删除的节点
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                	// 删除树中的节点
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                	// 这是链表的头节点
                    tab[index] = node.next;
                else
                	// 删除链表中间的一个节点
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

8.克隆

    public Object clone() {
        HashMap<K,V> result;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
        // 初始化参数
        result.reinitialize();
        // 这个函数里面就是遍历了原来的map,然后依次put进新的map中
        result.putMapEntries(this, false);
        return result;
    }

总结

源码总结

1.扩容

扩容触发条件:

  • 容量为0的时候插入元素,触发的初始化扩容;
  • 现有键值对数量大小是否大于扩容阈值,所谓扩容阈值,就是容量与加载因子的积,默认是0.75;
  • 如果在数组容量小于默认最小树化阈值64的时候触发了树化,那么就会进行一次扩容;
  • 对于put操作,扩容是发生在元素添加之后,这与List不同。

扩容的大小:

  • 初始默认容量是16。
  • 每次扩容的大小是2的幂次。

这里有两个容量的概念,一个是数组的数量,还有一个是键值对的数量,触发扩容的条件是判断键值对,而扩容的扩的数组的大小。上面限制最大容量是限制数组的大小,而键值对的大小能多得多。

2.树化

树化的条件:

  • 当一个槽里的链表节点数大于等于树化阈值8,就可能会将链表生成红黑树。
  • 树化的还有一个条件是 键值对的容量必须大于64,这样可以避免一开始的时候数组比较小,大量的节点刚好被放到一个槽中,导致不必要的转化。

树退化的条件:

  • 如果树的节点数小于退化树阈值,就会将红黑树退化为链表。
  • 退化树阈值默认为6。

问题总结

为什么扩容发生在put操作之后?
Map的put操作不一定会发生添加新节点的行为,也可能是修改了原有的值,所以,操作末尾才能知道是不是添加了新的节点。
这样的缺点:但是如果扩容之前发生了树化,但是之后扩容会可能把树有拆分了,这样就浪费了性能,这是一个问题。如果以后不会再有数据插入,那就白扩容了。

为什么初始容量是16,且扩容的大小是两倍?
为了实现充分散列。
参考博客

key是null的情况:
从源码中的hash函数可以看出来,如果key为null的时候,hash值就是0,那么就会将键值对存储到数组的第0个位置。

和HashTable对比

  • 继承类不一样
    HashMap继承于AbstractMap,HashTable继承Dictionary。
  • 线程安全不同
    HashTable是此案从安全的,几乎所有的函数都是同步的。
  • 对key为null的处理不同
    HashMap支持key为null,哈希值直接算作0,而HashTable不支持null。
  • 支持的遍历种类不同
    HashMap只支持迭代器,而HashTable支持迭代器和枚举器。
  • 迭代器的遍历顺序不同
    HashMap从前往后,HashTable从后往前。
  • 初始容量和扩容值不同
    HashMap初始容量16,每次扩容2倍,而HashTable初始容量11,每次扩容2倍 + 1.
  • hash值的算法不同
    HashMao采用自定义的哈希算法,哈希更加均匀,而HashTable直接使用key的hashCode()。
原文地址:https://www.cnblogs.com/lippon/p/14117605.html