Java-HashMap源码解析

HashMap源码解析

transient Node<K,V>[] table;        //HashMap的哈希桶数组,非常重要的存储结构,用于存放表示键值对数据的Node元素。

  transient Set<Map.Entry<K,V>> entrySet;  //HashMap将数据转换成set的另一种存储形式,这个变量主要用于迭代功能。

  transient int size;             //HashMap中实际存在的Node数量,注意这个数量不等于table的长度,甚至可能大于它,因为在table的每个节点上是一个链表(或RBT)结构,可能不止有一个Node元素存在。

  transient int modCount;           //HashMap的数据被修改的次数,这个变量用于迭代过程中的Fail-Fast机制,其存在的意义在于保证发生了线程安全问题时,能及时的发现(操作前备份的count和当前modCount不相等)并抛出异常终止操作。

  int threshold;                //HashMap的扩容阈值,在HashMap中存储的Node键值对超过这个数量时,自动扩容容量为原来的二倍。

  final float loadFactor;           //HashMap的负载因子,可计算出当前table长度下的扩容阈值:threshold = loadFactor * table.length。

PUT值!!

put方法,put方法的入参就有两个值:key和value。

public V put(K key, V value) {
   return putVal(hash(key), key, value, false, true);
}

可以看到具体的实现不是在这,里面有个putVal的方法,所有的逻辑都在这个PutVal方法中。

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    // tab:即table数组,p:数组下标i存储的链表或者红黑树的首节点,n:数组的长度,
    // i:哈希取模后的下标
        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;
    // 如果哈希取模后对应的数组下标节点数据为空,则新创建节点,当前k-v为节点中第		一条数据 
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
    // 当不为空时
        else {
            Node<K,V> e; K k;
            // 如果当前k-v与首节点哈希值和key都相等,赋值p->e
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 当前节点为红黑树,按照红黑树的方式添加k-v值
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            // 判断节点类型为链表类型,循环遍历链表 这里只是添加新的而不处理同一个元素value的更新
            else {
                for (int binCount = 0; ; ++binCount) {
                    // 节点为尾部节点,当前k-v作为新节点并添加到链表的尾部
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 当节点数>=8 转化为红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 当前遍历到的节点e的哈希值和k-v相等,则退出
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 当前节点不是尾节点,e->p 继续遍历
                    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;
    // 如果当前map中包含的k-v键值超过了阈值threshold则扩容
        if (++size > threshold)
            resize();
    // 空函数
        afterNodeInsertion(evict);
        return null;
    }
  1. 新值添加到链表尾部,如果链表长度达到8的时候,链表会转换为红黑树,优化了链表查询慢的问题。后续在resize中可以知道长度降到6的时候,红黑树会转为链表。
  2. map中k-v键值总数超过阈值(threshold)的时候会进行扩容,而 threshold的值是在resize里面计算的,初始化值为(int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY)16*0.75=12。从putVal方法中可以看到共有两次调用resize(),分别是初始化和扩容的时候。

putVal方法有5个入参,第一个入参似乎调用了一个hash方法传参是key。我们先看下这个 hash 方法。

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

HashMap中是通过对 key 的哈希取模后的值定位到数组的下标位置的,但是hash(key) % length的运算效率很低。在数学中hash(key) & (n - 1)的结果是跟hash(key) % n取模结果是一样的,但是与运算的性能要比hash对n取模要高很多。因此在源码中的tab[i = (n - 1) & hash]就是对数组长度做哈希取模运算。


对象的 hashCode 是一个 int 类型的整数,假设 key 的 hashCode 值是 h=514287204853,将其转为二进制格式。

image-20201116181520550

image-20201116181538635

h右移16位意味着将高16的值放在了低16位上,高16位补0,这样处理后再与h进行异或运算得到一个运算后的hash值。

从结果中可以得知,运算后的hash值和原来的hashCode值相比,高16位还是原来h的高16位,而低16位则是原来的高16位和低16的异或后的新值。

将这样的得到的hash值再与(n-1)进行与运算,n即为数组的长度,初始值是16,每次扩容的时候,都是2的倍数进行扩容,所以n的值必不会很大。它的高16位基本都为0,只有低16位才会有值。

而通过右移16位异或运算后,相当于是将高16位和低16位进行了融合,运算结果的低16位具有了h的高16位和低16位的联合特征。这样可以降低哈希冲突从而在一定程度上保证了数据的均匀分布。

自定义的Node类型

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V 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;
        }

初始化节点

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

get值 !!

public V get(Object key) {
        Node<K,V> e;
    // 根据key及其hash值查询node节点,如果存在,则放回该节点的value值
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

通过上面的方法,我们可以看出主要的函数内容都在getNode方法里。

final Node<K,V> getNode(int hash, Object key) {// 根据key搜索节点的方法。记住判断key相等的条件,hash值相同,并且符合equals方法
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    //根据输入的hash值,可以直接计算出对于的下标(n-1)&hash,缩小查询范围,如果存在结果,则必定在table的这个位置上。
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                // 判断第一个存在的节点的key是否和查询的key相等,如果相等,直接返回该节点
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 遍历该结构直到next为null
            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;
    }

查询过程不涉及hashmap的结构变变动,所以get方法的源码显得很简洁,核心算法是遍历table某特定位置上的所有值,分别与key进行比较是否相等。

相关资料:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值