Java中HashMap的底层实现

1.底层存储特征

HashMap底层实现采用了哈希表,这是一种非常重要的数据结构。

数据结构中由数组和链表来实现对数据的存储,各有特点。

那么能否结合数组和链表的优点(查询快,增删效率高),答案就是哈希表,哈希表的本质就是“数组+链表”

下图为基于1.8版本的HashMap示意图,在链表中添加元素会放到链表的末尾。如果节点个数大于8时转换为红黑树。如果红黑树中节点个数小于6时转换为链表。

 2.成员变量

//初始长度为16,必须为2的n次方
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
/**
* 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;
//数组扩容负载因子,当数组长度为12个元素的时候,就要进行扩容
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表的长度为8时,转换为红黑树
static final int TREEIFY_THRESHOLD = 8;
//将红黑树转换为链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;
//数组长度超过64才会对长度为8的链表进行树形化处理
static final int MIN_TREEIFY_CAPACITY = 64;
//键值对的数量
transient int size;
//Node类型的数组
transient Node<K,V>[] table;

3.HashMap中存储元素的节点类型

//静态内部类,定义节点
static class Node<K,V> implements Map.Entry<K,V> {  //Map.Entry获得的就是Node
    final int hash;   //存放HashCode值
    final K key;     //存放key,key不能被修改
    V value;      //存放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;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;

        return o instanceof Map.Entry<?, ?> e
                && Objects.equals(key, e.getKey())
                && Objects.equals(value, e.getValue());
    }
}
//定义红黑树时候节点对象的定义
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);
    }
	...
}//这玩意太长了,放一部分就行
//红黑树节点对象,TreeNode继承了Node
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);
    }
}
//Node实现了Entry接口,Entry类继承了Node类,TreeNode继承了Entry

4.数组初始化

数组初始化,延迟初始化,通过resize方法实现初始化处理,resize既实现数组初始化,也实现了数组扩容处理。

//数组初始化,resize方法
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;  //table是null
    int oldCap = (oldTab == null) ? 0 : oldTab.length;  //返回0
    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)  //这里是进行两倍扩容,newCap第一次等于32
            newThr = oldThr << 1; // double threshold,阈值由原来12乘2变为24
    }
    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;  //长度为12,如果扩容为24
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];  //创建一个长度16的Node数组
    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;
}

5.计算Hash值

  • 获得key对象的hashcode,首先调用key对象的hashcode()方法,获得key的hashcode值。

  • 根据hashcode计算出hash值(要求在[0,数组长度-1]区间)。hashcode是一个整数,我们需要将它转化成[0,数组长度-1]的范围,我们要求转化后的hash值尽量均匀地分布在[0,数组长度-1]这个区间,减少"hash冲突"。

    一种极端简单和低下的算法是:

    hash值 = hashcode/hashcode

    也就是说,hash值总是1,这意味着,键值对对象都会存储到数组索引1的位置,这样就形成一个非常长的链表。相当于每存储一个对象都会发生“hash冲突”,HashMap也退化成了一个“链表”。

    另一种简单和常用的算法是相除取余算法:

    hash值 = hashcode%数组长度

    这种算法可以让hash值均匀的分布在[0,数组长度-1]的区间。但是,这种算法由于使用了除法操作,效率低下。JDK后来改进了算法。首先约定数组长度必须为2的整数幂,这样采用位运算即可实现取余的效果。hash值=hashcode&(数组长度-1)。

看源码

static final int hash(Object key) {  //返回了一个预处理,并不是真正的hashcode,为了结果更加散列
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //32位长度,取出的高16位与低16位的值做异或运算
}

	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)  //15的二进制与hash结果与运算,决定最后放到哪里
            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 {     //key不相同的,实现节点的插入
                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);   //如果长度超过8,转成树
                        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;  //这里e.value是原来key对应的value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;    //这里的value是传进来新的value值,完成了value覆盖
                afterNodeAccess(e);
                return oldValue;   //返回旧的value
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

6.添加元素

添加元素,源码看上面,下面是链表做树形化的方法

//链表树形化
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();    //数组小于64,先做扩容处理
    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);
    }
}

7.数组扩容

//数组扩容,还是上面putVal源码中内容
++modCount;
if (++size > threshold) //判断数组是否需要做扩容,threshold是判断是否扩容的阈值
    resize();  //resize()方法在上面有,往上翻,按照两倍扩容
afterNodeInsertion(evict);

Guess you like

Origin blog.csdn.net/lipengfei0427/article/details/121537810