Java 之HashMap源码简单分析

前言

通过了解HashMap的数据结构、put、get等源码来更加深入理解HashMap,便于更好的编程。

一、数据结构

HashMap 底层使用哈希表,用一个数组+多个链表(或多个红黑树)来实现。
数组:连续内存,寻址快,但增加删除效率低。
链表:不连续内存,寻址慢,但增加删除效率高。
HashMap 通过 hash 的方式结合数组与链表的优点,形成HashMap。
在这里插入图片描述

二、成员变量

/**
* The default initial capacity - MUST be a power of two.
*/
//默认初始化长度,1左移4位,就是2的4次方 为 16,特别强调初始容量必须是2的n次方,对数组元素做hashCode需要这样的数组长度。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
/**
* 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次方,这里也必须是2的n次方才行。
//如果隐式指定了更大的值,则使用这个MAXIMUM_CAPACITY,由具有参数的构造方法之一执行.
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
//负载因子是数组扩容的负载因子,数组长度不够时才扩容吗?当数组容量用到75%时,就对数组进行扩容,可以避免太多冲突。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表的长度达到8时,链表转化成红黑树。
static final int TREEIFY_THRESHOLD = 8;
//当红黑树节点个数减到6了,就将红黑树转化成链表。
static final int UNTREEIFY_THRESHOLD = 6;
//当数组的长度大于等于60时,才能对链表节点增到8的转化为红黑树。
static final int MIN_TREEIFY_CAPACITY = 64;
//记录Map中有多少键值对
transient int size;
//数组
transient Node<K,V>[] table;

三、节点类型

1)链表,静态内部类 static class Node<K,V> implements Map.Entry<K,V>

//实现了Map.Entry<K,V>接口,其本质是Node
static class Node<K,V> implements Map.Entry<K,V> {
		//hash 值,不可修改
        final int hash;
        //不可修改的key,可修改value,同一key,后进的value会覆盖掉前面的value,
        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;
        }
		//平时使用Entry的getKey和getValue
        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        //重写toString
        public final String toString() { return key + "=" + value; }
		//重写hashCode的求法,也是hash函数的关键,这里采用key和value的hashCode值再异或起来。
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
		//为特定key的Node节点update value
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
		//重写equals方法,要么地址相等,要么在另一个对象也是实现Map.Entry的情况下,key和value都必须相等,才返回true
        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;
        }
    }

2)树型,静态内部类static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>

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

注:LinkedHashMap.Entry<K,V>中的静态内部类Entry<K,V>,它又继承自HashMap.Node,所以链表的Node是TreeNode的一个父类,正因为如此,数组中的next才能够指向红黑树的root。

	static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

在这里插入图片描述

四、数组初始化

采用懒加载,并没有去初始化一个数组,而是在添加第一个元素时进行初始化数组并扩容。
注:只看有注释,我们关心的部分。

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

添加元素

	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;
        //table数组没有初始化,它是为null,所以满足条件,去resize()
        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;
    }
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //刚开始oldCap == 0的,而且threshold也是默认为0,所以去看else
        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
        	//长度初始化为16,newThr初始化为16 * 0.75 = 12
            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设置为16 * 0.75 = 12
        threshold = newThr;
        //去new 一个新的数组newTab,长度为16
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        //赋值table
        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;
    }

注:只看有注释,我们关心的部分。

五、计算hash值

1)计算hashCode值(掉key对象重写的hashCode()),然后计算hash值(需高效率且均匀的分布在数组中),不会用取余的方式,因为CPU取余和模运算效率都低。这里采用的是异或运算,将key对象的hashCode值无符号右移16位,然后与hashCode值异或,即把其高16位与低16位做一个异或运算,由于高16位于0异或,保持不变。
这样会hash得更均匀一些。

	static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    //putVal函数中把计算出的hash值转化成数组下标如下,通过&运算,所以为什么数组扩容的长度为什么是2的n次方了,2的n次方-1就是全1,相当于取后n位的值。
    if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

六、添加元素

	public V put(K key, V value) {
		//计算hash值,然后去putVal
        return putVal(hash(key), key, value, false, true);
    }
    //通过高16位与低16异或得到hash值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    //要么覆盖同样的key的value,即覆盖hash值相同的value;要么把新的key,value添加在链表后面或红黑树中。
	final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //局部变量,用来获取Node数组tab,相同hash值的Node p,Node数组的长度n,取Node时要用的index,即i
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果数组为null或者数组为空,就去做一个扩容,后面会专门解释resize扩容机制。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //通过与运算快速计算出均匀的hash值,如果该位置为空,就直接将newNode放入数组对应位置。
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //否则就是有冲突的情况
        else {
        	//局部变量需不断next的临时节点,和传入进来的key
            Node<K,V> e; K k;
            //hash值相同,key也相同,是同一个key,此时为覆盖value做准备
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //此时该位置的Node存的是Node的子类Tree Node,说明是一颗红黑树,采取红黑树putTreeVal的特殊处理
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //既不是覆盖value,也不是接的红黑树,那么就是接的一条链表
            else {
            	//不断next找到链表尾节点
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //找到尾节点,而且已经接上了newNode,需判断是不是链表长度大于8了,这个时候可能需将链表转化了红黑树,代码见下。
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //当然在链表上也可能碰到同一key且hash值相同,需要为覆盖value做准备
                    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;
        //如果是覆盖的情况,就已经return oldValue了,否则进行size++,再判断是否超过阈值,开始扩容。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

是否要转化为红黑树

	final void treeifyBin(Node<K,V>[] tab, int hash) {
		//局部变量数组长度n,取Node的下标index,取到了Node e
        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);
        }
    }

七、扩容机制

	final Node<K,V>[] resize() {
		//要扩容先取到原来的数组oldTab
        Node<K,V>[] oldTab = table;
        //获取原来数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //不是懒加载的扩容
        if (oldCap > 0) {
        //MAXIMUM_CAPACITY是30位,大于等于它时,阈值就只能设为最大int数,其实这里只可能等于,看下面的else if  (newCap = oldCap << 1) < MAXIMUM_CAPACITY
            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"})
        //新的table
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        //table新的指向
        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;
    }

总结

1)数据结构,Node数组+Node链表或Node 红黑树。
2)成员变量,容量和阈值,初始化的空数组。
3)节点类型,Node<K,V>
4)数组初始化,懒加载,put时才扩容。
5)计算hash值,异或 、与运算,做到均匀的分布
6)添加元素,putVal()
7)扩容机制,resize()

参考文献

[1] Java SE oldLu
[2] [JDK 1.12]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值