Java集合 HashMap解析(源码分析)

目录:

一、数据结构
二、常用构造
三、常用属性
四、常用方法put()
五、常用方法get()
六、常用方法remove()

一、数据结构

1.hashmap的数据结构由数组+链表(链表太长的话就转化为红黑树)
2.继承map的键值对
3.hashMap数据结构图解;
在这里插入图片描述

二、常用构造

1. 4个常用构造的了解

在这里插入图片描述

2. 我们重点了解1 无参构造(看源码)

【初始化容量 16,负载因子 0.75】
在这里插入图片描述

三、常用属性

只有一些常量,无常用属性

四、常用方法put()

1.put()方法

在这里插入图片描述

2.put()方法调用的hash(key)方法

在这里插入图片描述

3. (重点)put()方法调用的putVal()方法。

源码:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //【1,如果table 没有初始化,就resize()初始化.】
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //【2.通过hash值找到元素的位置,如果元素value为空,将数据存放进去。创建新的node。】
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    //【3.如果hash值对应的value有值?】
    else {
        Node<K,V> e; K k;
        //【3.1 如果hash值相等,并且key值相等。就替换】
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //【3.2如果key值不相等,且挂在hash值数组上的,key的数据结构为 TreeNode。使用红黑树插入。】
        //【新增知识点:红黑树插入putTheeVal()】
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        //【3.3 如果key不等,且有不用红黑树,就是用链表插入。】
        else {
            //3.3.1循环哈希值hash  p  下的所有链表。
            for (int binCount = 0; ; ++binCount) {
                //3.3.2.1 如果下一个链表为空,就新增加新的链表。
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //3.3.2.2 如果链表的的长度过长,就把链表转化为红黑树。
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                //3.3.3 ,判断插入成功,跳出循环。
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //【3.4经过上面的循环,如果e不为空,就证明插入成功,更新指定位置的键值对。】
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //【4.添加后再次判断大小,过大就resize()扩容】
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

总结:
1.如果table没有初始化,就会对table进行resize()初始化
2.如果 初始化 且 hash值未知的的为空,就直接将存放。
3.如果初始化 且不为空就执行以下操作,插入
(1)3.1 如果hash值相等,并且key值相等。就替换
(2)3.2如果key值不相等,且挂在hash值数组上的,key的数据结构为 TreeNode。使用红黑树插入
(3)else 不为红黑树,为链表执行以下操作

  • 1.遍历链表
  • 2.下一个为空,就插入数据,(1)2.插入后判断链表长度,如果过长,就转换为红黑树。
  • 3.如果插入成功,就break。问题:链表上的所有key没有判断是否和插入的key相等啊?

(4)红黑树或者链表插入完成后,更新键值对
4.插入完成后就再次判断大小,如果过大就扩容。

4. resize()方法

/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 * 【初始化默认容量,或者增加容量在2次幂偏移,容量大小*2 】
 *
 * @return the table
 */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    //【1.旧容量oldCap > 0 (已经初始化)】
    if (oldCap > 0) {
        //【1.1 旧容量 >= 最大值,就不再扩容,把阈值设置为最大值】
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //【1.2.如果容量还可以扩容,就扩大 2倍。】
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    //【2.旧容量>0不成立,但旧阈值(threshold门槛) > 0,把旧门槛的值赋值给新的 容量】
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //【3.如果1,2都不成立,容量和门槛都为0,初始化阈值和门槛为默认值】
    //这里解决了 无参构造方法,不对阈值和容量进行初始化的问题。
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //阈值为0??
    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"})
    //【4.更新数据桶(哈希值的数组链条,用来保存不同的哈希值,下面挂着链条或者红黑树,】
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    //【5.把旧的数据移动到新数据桶里面】
    //如果之前的数组桶里面已经存在数据,由于table容量发生变化,hash值也会发生变化,需要重新计算下标
    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;
}

总结:
1.判断是否初始化,没有初始化就初始化容器和阈值
(1)如果初始化了 且 扩容后不超过 阈值,【扩容 2倍】
(2)超过阈值,就让阈值等于新的容量
2.扩容后创建新的table数据桶,把旧的数据移动到新的数据桶里
(1)如果hash值的位置为空,就直接插入值
(2)如果hash值位置为链表,就重新计算下标,分组链表
(3)如果是红黑树,就拆分操作。
注意:这个地方有些东西看不懂,等下回头再研究,现在了解他的具体使用就可以了。

五、常用方法 get()

1。get()方法

在这里插入图片描述

3. getNode()方法

    /**
     * Implements Map.get and related methods.【实现get()的方法 getNode()】
     *
     * @param hash hash for key【获取key的hash】
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //【1.如果第一个值就是 查找的 key,直接诶取出】
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //【2.如果第一个值不是,且是树结构TreeNode,就是用树查找】
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //【3.链表,就是用遍历链表的查找】
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

总结:
1.第一个key匹配,直接诶取出
2.第一个key不匹配,且是树结构 TreeNode,就是用树查找
3.第一个key不匹配,且是链表结构,就是用遍历链表查找

树查找等待补充

六、remove()方法

1.remove()

在这里插入图片描述

2. removeNode()方法

 /**
  * Implements Map.remove and related(相关的) methods.
  * 【实现 Map.remove() 的相关的方法】
  *
  * @param hash hash for key
  * @param key the key
  * @param value the value to match if matchValue, else ignored
  * @param matchValue if true only remove if value is equal
  * @param movable if false do not move other nodes while removing
  * @return the node, or null if none
  */
 final Node<K,V> removeNode(int hash, Object key, Object value,
                            boolean matchValue, boolean movable) {
     Node<K,V>[] tab; Node<K,V> p; int n, index;
     //【1.更具hash值查找对对应的数组的位置】
     if ((tab = table) != null && (n = tab.length) > 0 &&
         (p = tab[index = (n - 1) & hash]) != null) {
         Node<K,V> node = null, e; K k; V v;
         if (p.hash == hash &&
             ((k = p.key) == key || (key != null && key.equals(k))))
             node = p;
         else if ((e = p.next) != null) {
             if (p instanceof TreeNode)
                 node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
             else {
                 do {
                     if (e.hash == hash &&
                         ((k = e.key) == key ||
                          (key != null && key.equals(k)))) {
                         node = e;
                         break;
                     }
                     p = e;
                 } while ((e = e.next) != null);
             }
         }
         //【2.如果找到,就进行移除】
         if (node != null && (!matchValue || (v = node.value) == value ||
                              (value != null && value.equals(v)))) {
             //【2.1 如果是该 hash值的位置是 挂了一颗 红黑树,就进行“树移除”】
             if (node instanceof TreeNode)
                 ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
             //【2.2 如果挂了 链表,就把索引指向下一个链表就可以了】
             else if (node == p)
                 tab[index] = node.next;
             else
                 p.next = node.next;
             ++modCount;
             --size;
             afterNodeRemoval(node);
             return node;
         }
     }
     return null;
 }

总结:和get()方法几乎一致。

七、遇到的其他方法解析

1.hash()方法,

1.代码

 static final int hash(Object key) {
    int h;
    //【hash()返回hashCode的计算后的值】
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

2,总结:
这个代码叫做扰动函数,也就是 hashCode()中的 的hash运算,如下
(1)获取key的hash值(hashCode()),根据地址获得的int值
(2)hashCode右移动 16位,并且和 原来的 hashCode进行 ^(异或运算 不同为真 1??),(让高低位进行混合,让两者都参与运算,让hash值更加均匀)

2. 取模运算 (n-1)& hash

HashMap 的很多源码中可以看到类似的表达。

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

hash算法中,为了高速度地让元素分布更加均匀,使用特殊取模运算。因为&的效率要远远大于 %,并且只有在 n 为 2的次幂的时候 才能有取模的效果。
由HashMap哈希算法引出的求余%和与运算&转换问题

参考博客:
https://juejin.im/post/5c8f461c5188252da90125ba#heading-2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章