jdk源码有感-HashMap

104 阅读3分钟

Hashmap

在jdk1.8中底层数据结构变成了 数组+链表+红黑树

引入红黑树优化了Hashmap的查询效率,为什么呢?

链表的查询需要一个个遍历链表中的结点,时间复杂度为O(n), 而红黑树的查询的时间复杂度为O(logn),查询效率比链表高

现在来看看Hashmap中的成员变量吧

默认容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
链表转红黑树的节点阀值
static final int TREEIFY_THRESHOLD = 8;

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
}

这边可以看到Node中存放了key和value的键值对,而且只有一个next指针,说明是单向链表结构

大家都知道,Hashmap的插入原理:根据key获取对应的hashCode值,然后对hashCode对数组长度取模,这样就可以得到key对应在数组中的index位置。
下面先来看看是如何获取hashCode的:

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

从源码中可以看出,hashCode的值的获取并没有像想象的直接h=key.hashCode,而是通过低16位与高16位进行异或运算得到的。 假设

这边大家可能会有个问题?为什么需要对key.hashCode的低16位与高16位进行异或,直接取key.hashCode不行嘛?带着这个疑问我们来看下面这段代码:

if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

i = (n - 1) & hash就是key对应在数组中的位置,假设n取默认值16

一般n的大小都是不会很多,那么n-1的高16位都为0,与运算的时候0&0=0,0&1=0,也就是高16位根本没有参与到寻址中,就没啥作用了。

上面对key.hashCode的低16位与高16位进行异或,这样同时保留了高16位与低16位的特征,降低了hach冲突的概率。目的就是减少hash冲突!

下面来看看put()方法:

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

寻址到index 位置后,会将新的Node<key,value>加入到链表尾部,如果链表的长度>=8时,链表会转变成红黑树

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);//这边把双向链表调整成红黑树的结构
        }
    }

会先把链表结点转变成树结点,然后由单向链表变成双向链表,最后把双向链表调整成红黑树的结构
当数据一个个插入之后,size>=容量*负载因子的时候,会进行扩容操作

if (++size > threshold)
            resize();
//数组扩容后,数组长度为原来的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
                
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

数组扩容后,原结点的在数组中index值也需要重新计算,这里巧妙的用(e.hash & oldCap) == 0,把结点放到原index位置或者 index+oldCap位置 oldCap=原数组长度

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

get()操作也就是hash寻址到对应的index位置,然后遍历链表或者红黑树,找到对应的结点