java的hashmap详解

背景

hashmap作为java使用最多的容器,不管是实际工作中还是面试中都是经常看到的,这里详细说明下HashMap的设计

术语

查看代码的过程会遇到很多术语以及单词,这里先梳理下

  • table 指的是hashtable,里面存放着桶
  • burket 桶,也就是数组的元素,里面内容是对应key的hash值
  • capacity 桶的大小,也就是数组的长度
  • bin 桶对应的链表或者数中的节点,就是最终的数据
  • load factor 加载因子,用于计算threhold
  • threhold 通过table的capactiy跟load factor的乘积计算而来
  • Node 链表数据结构,是单向链表
  • TreeNode 红黑树的数据结构

特性

引入红黑树

从1.7之后hashmap内部数据结构引入了红黑树,具体是,当bin的数据大于 TREEIFY_THRESHOLD 代码设置成8,会从单向链表转换成红黑树来存储,来提高速度, 当小于 UNTREEIFY_THRESHOLD 代码设置成6,会从树结果转换成单向链表。

这里说下,8 跟 6 的来源是,首先单向链表的平均查询速度是 O(N/2),而红黑树的查询速度是O(logN),这样我们发现当N=8的时候红黑树的算的3,单向链表是4,所以说明当个数是8是,红黑树的查找是优于链表,但是N=6是,树的查找速度是2.5,取整为3,这样跟链表的速度是等效的,所以选择低于6的就切换成链表,因为链表节省空间。那么中间7是什么状态,至于6-8这个区间,是折中区域为了防止同一个桶中元素频繁的增删增删,导致树化或者去树化的操作。

这里还有一个参数需要注意, MIN_TREEIFY_CAPACITY 这个源码是设置成64,官方描述当hashtable的容量capacity小于这个值后,采取扩容而非树化来处理哈希冲突,刚才不是说了当冲突个数达到 TREEIFY_THRESHOLD 也就是 8 的时候,应该将冲突元素进行树化处理吗,这里是说当hashtable的容量低于 MIN_TREEIFY_CAPACITY 时,应该采用扩容来处理冲突扎推了。同时这个数值设置成至少 4 倍 的TREEIFY_THRESHOLD,这里又要注意源码中初始的数组长度是 DEFAULT_INITIAL_CAPACITY 是16, 因为要4倍,所以就是64。

操作

添加元素

经典问题,hashmap的增加元素的步骤,可以分解为如下

  1. 计算key对应hash值
  2. 通过hash值在数组找到对应的桶
  3. 通过key.equal来处理冲突

计算hash值

源码是这么写的

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

这段代码成为扰动函数。我们知道hashtable的长度是有规律的是2的幂次方,初始化的长度是16,我们通过hash值来计算对应的桶的位置也是通过数组长度-1然后对hash值作“与”操作,例如我们初始化的数组长度 DEFAULT_INITIAL_CAPACITY 是16,对应-1之后的15的2进制码是1111,通过这个对hash值做与操作,由于15的高危都是0,所以能保证在数组找到对应的下标。

这里就有问题了,如果直接使用hash值做刚才的操作会发现,hash值高位的值没有用到,也就是你的hash函数多么均匀也会丢失高位的分布特性,所以我们采用将高位(h>>>16)跟低位 (h) 进行异或XOR来保留高位的信息,因为int是32位的,所有高位往右移动16就是可以跟低位16就行异或了,如果有人疑问为什么是异或而不是或或者与操作,那是因为或跟与都是只考虑一边特性的,例如或,如果低位为1,那么高位是0或者1,最后结果都是1,所以就也相当于丢失了高位特性,同理与操作。

计算数组下标

摘自putVal源码

p = tab[i = (n - 1) & hash]

这是计算下标,原因是hashtable的长度是有规律的是2的幂次方,初始化的长度是16,我们通过hash值来计算对应的桶的位置也是通过数组长度-1然后对hash值作“与”操作,例如我们初始化的数组长度 DEFAULT_INITIAL_CAPACITY 是16,对应-1之后的15的2进制码是1111,通过这个对hash值做与操作,由于15的高危都是0,所以能保证在数组找到对应的下标。

处理冲突

我直接在源码写注释来辅助理解,特殊困难点,我放到后面说明

    public V put(K key, V value) {
        // 利用前面说的扰动函数来计算hash值
        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;
        // 这单代码只用于初始化,来初始化数组
        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;
            // 判断链表的头结点跟树的根节点是否key一致
            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);
                        // 如果节点数大于等于7就树化
                        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;
                }
            }
            // 如果是已有节点的处理,根据onlyIfAbsent来特殊处理,更新内容,返回旧值
            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();
        // 用于LinkHashMap留的,自身是空函数
        afterNodeInsertion(evict);
        return null;
    }

注意:结构更新计数器用于迭代器的,后面专门讲迭代器的时候细说。

查询元素

跟加入元素基本类似,也是分计算hash值,寻找数组下表,通过key.equals函数获取元素

    public V get(Object key) {
        Node<K,V> e;
        // 计算hash值,具体原理参考前面
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 当数组不为空且数组下标不为空时找到UI对应桶
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 判断链表的头结点跟树的根节点是否key一致
            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;
    }

删除元素

跟加入元素基本类似,也是分计算hash值,寻找数组下表,通过key.equals函数获取元素

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
    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; // 这里p是指向上一个节点
                    } while ((e = e.next) != null);
                }
            }
            // 上面跟get类似,这里是删除部分的逻辑
            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是指向上一个节点
                    p.next = node.next;
                ++modCount;
                --size;
                // 用于LinkHashMap留的,自身是空函数
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

HashMap扩容机制

    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
                        // 1.8的改进,本质还是利用了hashmap的长度是2的幂次方的原理,具体参考后面说明
                        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;
    }

代码里面如果是数据结构是链表,具体的扩容是采用跟旧容量做与操作来确定新其新的位置,新的位置有可能是当前下标,也有可能是下表加上旧数组大小

后面用具体的例子来说明

img

  1. 假设一开始hashmap的数组是原始大小16,在下表0的位置有3个bin,分别对应dhashcode的低8位是00(0000 0000), 30(0011 0000), 50(0101 0000),他们在就数组对应的下表通过跟15(2^4-1=16-1)进行与操作得到是0
  2. 代码中 if ((e.hash & oldCap) == 0) 通过判断元素哈希值跟旧数组的大小做与操作,所以第一个元素00,对应的新的小标是0, 第二个元素就被计算到新的位置16(0001 0000),同理第三个,同时我们可以看出这两个新位置之间差16也就是旧数组的长度。

hashmap的容量为什么是1<<30

主要有两个原因导致

  1. java没有无符号的类型,最高位是符号位,也就是如果是10000000,在java里面就是-2^31也即是-2147483648,以下是java的源码
    /**
     * A constant holding the minimum value an {@code int} can
     * have, -2<sup>31</sup>.
     */
    @Native public static final int   MIN_VALUE = 0x80000000;

    /**
     * A constant holding the maximum value an {@code int} can
     * have, 2<sup>31</sup>-1.
     */
    @Native public static final int   MAX_VALUE = 0x7fffffff;
  1. 那么不选择0x7fffffff,而是1<<30,这是因为hashmap的长度是2的幂次方,所以只能选择1<<30,也就是2的30次方
class HashMap {
        /**
     * 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.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值