图解HashMap底层

前言:HashMap是在jdk1.2之后java增加的一种线程不安全的数据结构,底层数据结构在jdk1.7是数组+链表,而在jdk1.8之后是数组+链表+红黑树
1.首先我们先来看看它的源码,可以看到,他是继承了抽象类AbstractMap,实现了Map接口;其他的两个分别是克隆和序列化的标记接口;
在这里插入图片描述
2、我们再看看他的属性
可以看出啊,他官方的意思是默认的长度是1左移4位【就是16】,
最大长度是1左移30位;负载因子是0.75;可能看到这有些胖友会想负载因子啥意思呢?负载因子就是整个HashMap的可最大容纳的数据是容量 * 0.75,也即是当大于12的时候就要扩容,以2的倍数扩容,避免哈希冲突,
在这里插入图片描述


在这里插入代码片
接下来看看他是怎么增加数据的,我们来看源码
这截图看不清,我把源码复制过来,大家一起看看

/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key}.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
 * Implements Map.put and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
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) {
                    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;
}
     

在这里插入图片描述
4、大概意思就是在增加元素的时候,会先去根据key找到早数组中的位置,如当前位置不存在元素,则直接把值放在数组中即可;如当前位置存在元素,则根据key找到相应的哈希值与当前链表中已存在的所有key的哈希值比较,如存在相同的哈希值,则将相同的已存在的key对应的value覆盖,key不变;如不相同,则把元素放在链表尾部【jdk1.8以上;jdk1.7版本元素是放在头部,但是可能会造成元素逆序和形成环形链表死循环】;
当链表长度不小于8【即是大于等于8,由源码可知】是就转化为红黑树,接着往下看,转化为红黑树的是因为:
你想一下!红黑树的时间复杂度是O(logn),链表的时间复杂度是O(n),假设当元素等于8时,红黑树查找平均要log8 = 3次,链表要8/2=4次,所以当超过长度不小于8时转化为红黑树的查询效率较好,在这里有的胖友可能还有疑问?那为什么量表长度又要不大于6呢,其实我理解的是这样的,其实由两条曲线的特性可知,当链表长度大于4的时候红黑树的查找效率是比量表的好的,但是链表在转化成为红黑树的时候也会需要一定的时间,需要消耗系统资源的,而且在长度为4-8间时其实执行效率也相差不大,并且链表长度大于8的概率很小,因扩容机制使得的哈希桶的每一个添加的元素都均匀分布在每个桶中,即是每个桶中的元素个数都差不多一样的多,满足泊松分布;

在这里插入图片描述
5、HashMap的扩容机制,为啥是要长度乘以2?
首先不管乘以多少,他扩容的目的得清楚:保证新添加的元素能分布在每个HashMap的桶的概率是一样的,提高哈希表的内存空间的利用率,想一下:每当新添加的元素都在同一个桶上产生哈希碰撞,一直不停往一个桶上不断的累加元素,而其他的桶中却少有元素甚至没有元素,那么就会造成很多大量的内存空间浪费;
那为啥乘以2就能达到这个目的呢?
看源码可知:当添加一个元素时,若key不为空,ze会去调用Object类的hashcode方法得到哈希值,在与这个哈希值无符号位右移16位得到的值与原来的哈希值取异或;最终得到的值再去与扩容后的长度-1取 & ;
例如:我添加两个元素,他们的经过以上的一系列操作变化之后的最终值分别为3和4,现在我们扩容之后的长度为16,
那么3 & (16-1)——>>0000000000000011 & 0000000000001111 ——>>0000000000000011=3
4 & (16-1)——>>0000000000000100 & 0000000000001111 ——>>0000000000000100=4
两者不相同,则分布在每个桶上的概率都是一样的
反之,如长度是13,
那么3 &(13-1),3 &(13-1)和4——>>值是一样的,则就会在同一个桶上发生碰撞,空间利用率就低,
这就是为什么要长度乘以2,yin乘以2之后减一他的二进制16位处理高位是0,之外其余全是1,那么两者的结果就取决于另一个数的值,
在这里插入图片描述
在这里插入图片描述
添加元素方法:

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

6、最后我们来谈谈它的时间复杂度吧
他时间复杂度有三种情况,得看数据结构:
数组:O(1);
数组+链表:O(1)+O(n);
数组+红黑树:O(1)+O(logn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值