美文网首页Java
一文看透HashMap底层实现原理

一文看透HashMap底层实现原理

作者: Java天天 | 来源:发表于2020-03-10 15:16 被阅读0次

    简单介绍

    HashMap基于哈希表,它实现了Map接口,以键值对形式存储数据,是Java程序员最常用的集合之一。它的键key不可重复但可以为null,值value可以重复可以为null,元素存取无序,并且存储元素时如果已经有该键会采用新值覆盖旧值的策略。

    HashMap采用的数据结构

    由于HashMap是基于哈希表实现的,而哈希表随着数据的增加一定会有哈希冲突问题(鸽巢原理),解决哈希冲突的方式主要有两种:

    开放地址法:产生哈希冲突时,重新探测一个新的空闲位置,将其插入,适用于数据量小的情况

    拉链法:产生哈希冲突时,在冲突位置建立链表,并将其插入链表

    HashMap采用拉链法解决哈希冲突,他的数据结构是数组+链表(JDK1.8后采用数组+链表+红黑树)

    下面是它的实现代码,在JDK1.8之前是Entry内部类,JDK1.8后因为引入了红黑树变为了Node内部类。可以看到它的每一个节点都有key,value,指向下一个节点的next,还有hash(这个hash是为了便于进行比较,在后边的代码中可以看到)

    transient Node<K,V>[] table;

    static class Node<K,V> implements Map.Entry<K,V> {

            final int hash;

            final K key;

            V value;

            Node<K,V> next;

    }

    Hash算法

    哈希表结构中哈希算法尤为重要,首先不能太复杂,太复杂光计算就消耗太多的计算时间,其次生成的索引值要尽可能随机并且分布均匀。那么HashMap的哈希算法是如何设计的?

    下面截取了HashMap在JDK1.7和1.8版本下put()的部分源代码

    JDK1.7

    public V put(K key, V value) {

        // ...

        int hash = hash(key.hashCode());

        int i = indexFor(hash, table.length);

        // ...

    }

    static int hash(int h) {

        h ^= (h >>> 20) ^ (h >>> 12);

        return h ^ (h >>> 7) ^ (h >>> 4);

    }

    static int indexFor(int h, int length) {

        return h & (length-1);

    }

    JDK1.8

    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) {

        // ...

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

            tab[i] = newNode(hash, key, value, null);

        // ...

    }

    static final int hash(Object key) {

        int h;

        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

    }

    两者比较可以看出有一些共同点

    元素hash的计算采用的是JDK自带的hashcode()+移位操作;

    数组索引的计算采用的都是hash & (length - 1)。

    这和我们传统的认知是不一样的,我们先前计算数组散列后索引都是用%取余操作,那么HashMap为什么要用&与运算呢?而且还是和length - 1?

    我们使用几组数据进行测试:

    /**

    * The default initial capacity - MUST be a power of two.

    */

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    假设hash结果为0101 0101(只截取了后8位),数组长度采用默认长度16,那么length-1就是0000 1111

    h : 0101 0101

    15: 0000 1111

    & : 0000 0101  散列索引为5,属于[0, 15]区间 √

    结果貌似是对的,但是为什么呢?这是一个巧合吗?

    我发现length-1后,他的高28位全为0,低四位全为1,而根据&操作特性,他的结果中高28位肯定为0,

    而低四位就是hash的低四位,那么索引结果就是hash的低四位,而低四位的区间刚好就是[0, 15]。

    好吧,看来结果是对的!

    但是我还注意到,在数组长度前有一行注释,说长度必须是2的幂次?这又是为什么呢?

    我接着测试...

    hash结果还为0101 0101,数组长度长度为17,那么length-1就是0001 0000

    h : 0101 0101

    16: 0001 0000

    & : 0001 0000  散列索引为16,属于[0,16]区间 √

    这个结果是对的,但是我发现一个问题:length-1的低四位一直为0,那计算结果中低四位肯定为0;

    再看高位,高位只会产生两种结果(第27位是0/1),这样肯定不行的,散列结果只能是0/16。

    我没有发现什么规律,那么下一组数据...

    h : 0101 0101

    31: 0001 1111

    & : 0001 0101  散列索引为21,属于[0,31]区间 √

    我发现了,length-1的二进制表示中,如果高位全是0,低位全是1,可以奏效!

    那么反过来看,length必须是1xxx的,这刚好就是2的幂次表示。

    OK,这也就解释了为什么table数组要求长度为2的幂次

    解析put()源代码

    JDK1.7:null键直接放置在下标0处;非null键计算下标索引,使用头插法插入到下标索引对应的链表中。中间发现相同键,新值替换旧值,当容量超出HashMap阈值扩容为原长度的2倍

    public V put(K key, V value) { 

            // 键为null,将元素放置到table数组的0下标处

            if (key == null) 

                return putForNullKey(value);

            // 计算hash和数组下标索引位置

            int hash = hash(key.hashCode()); 

            int i = indexFor(hash, table.length); 

            // 根据索引找到链表,当hash一致,键一致,说明该键已存在,使用新值替换旧值并返回

            for (Entry<K,V> e = table[i]; e != null; e = e.next) { 

                Object k; 

                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 

                    V oldValue = e.value; 

                    e.value = value; 

                    e.recordAccess(this); 

                    return oldValue; 

                } 

            } 

            modCount++;

            // 插入链表

            addEntry(hash, key, value, i); 

            return null; 

        }

        private V putForNullKey(V value) {

            // 一样的,新旧值替换

            for (Entry<K,V> e = table[0]; e != null; e = e.next) { 

                if (e.key == null) { 

                    V oldValue = e.value; 

                    e.value = value; 

                    e.recordAccess(this); 

                    return oldValue; 

                } 

            } 

            modCount++; 

            // 插入到数组下标为0位置

            addEntry(0, null, value, 0); 

            return null; 

        }

        void addEntry(int hash, K key, V value, int bucketIndex) {

            Entry<K, V> e = table[bucketIndex];

            // 头插法:将新创建的Entry放入bucketIndex索引处,并且新Entry指向原来的

            table[bucketIndex] = new Entry<K, V>(hash, key, value, e);

            // 计数,扩容

            if (size++ >= threshold)

                resize(2 * table.length);

        }

    JDK1.8:计算数组索引下标,如果索引下标对应table[index]为null,直接插入;不为null,如果是红黑树节点就插入红黑树;如果是链表,就使用尾插法插入链表末尾。中间发现相同键,新值替换旧值,当容量超出HashMap阈值扩容为原长度的2倍

    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数组未初始化或长度为0,初始化、扩容(resize()既初始化又扩容)

        if ((tab = table) == null || (n = tab.length) == 0)

            n = (tab = resize()).length;

        // 计算数组索引下标,如果为null直接插入(写的太简洁了。。。)

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

            tab[i] = newNode(hash, key, value, null);

        else {

            Node<K,V> e; K k;

            // 当hash一致,键一致,说明该键在table中已存在,使用e保存(后边会实现新旧值替换逻辑)

            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) {

                        // 使用尾插法:将元素插入到链表末尾

                        /* 为什么1.7用头插法,1.8用尾插法?

                        我想应该是在1.8中引入了红黑树,在判断是否树化时有一个链表长度阈值,这个长度要一个个遍历,既然是要一个个遍历的话,就直接在尾部插入就好。而在1.7中他是不需要走到链表尾部的,采用头插法效率更高

                        */

                        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;

                }

            }

            // 新旧值替换逻辑,和1.7一样

            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;

    }

    解析get()源代码

    JDK1.7: null键去table[0]下找;非null键,根据key计算对应数组索引下标,遍历链表,找到相同键返回,没有返回null

    public V get(Object key) {

        // 键为null时,调用getForNullKey

        if (key == null)

            return getForNullKey();

        // 计算hash值 

        int hash = hash(key.hashCode());

        // 计算数组下标索引,遍历链表

        for (Entry<K, V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {

            Object k;

            // key相同,返回对应value

            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))

                return e.value;

        }

        // 没有该键,返回null

        return null;

    }

    JDK1.8: 根据key计算对应数组索引位置,先比较数组元素,匹配的话直接返回;不匹配,遍历其树结构或链表,找到后返回该节点,找不到返回null

    public V get(Object key) {

        Node<K,V> e;

        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;

        // 赋值,获取数组下标索引对应节点first

        if ((tab = table) != null && (n = tab.length) > 0 &&

            (first = tab[(n - 1) & hash]) != null) {

            // table[index]节点刚好就是要找的

            if (first.hash == hash && // always check first node

                ((k = first.key) == key || (key != null && key.equals(k))))

                return first;

            // 不是table[index]对应元素,遍历其链表或树

            if ((e = first.next) != null) {

                // 首节点是tree类型,遍历树

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

            }

        }

        // 找不到,返回null

        return null;

    }

    以上就是我的一些个人见解,如有误,还请大家指正!!!

    最后:


    上面都是自己整理好的!我就把资料贡献出来给有需要的人!顺便求一波关注。

    学习我们是认真的,拿大厂offer是势在必得的。 java(想了解更多点一下哦)

    原文链接:https://juejin.im/post/5e63b124518825494a3f9867

    相关文章

      网友评论

        本文标题:一文看透HashMap底层实现原理

        本文链接:https://www.haomeiwen.com/subject/emuwdhtx.html