【Java基础】HashMap 源码探究

文档注释

HashMap 是 Map 接口的实现类,实现了所有可选的操作,并且允许 null key 和 null value。(可以简单的理解与 HashTable 功能相同,除了它是不同步的,以及支持空值。)

存取效率:在存储的元素均匀分布在桶中时,get 和 put 元素的时间不变。遍历的效率与 capacity 相关,因此如果注重遍历的效率,不要把 capacity 初始值设的很大,或把负载系数设的很小。

非同步:不要用多线程同时修改。

image.png

一、类定义

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

继承自 AbstractMap,并实现 MapCloneableSerializable 接口。

一)实现的接口

CloneableSerializabel 都是标识接口,里面没有方法定义。实现这种接口仅用于标识这个类应该有这中功能。

Map接口中定义了要实现的方法,并且给出了部分方法的实现。
https://blog.csdn.net/weixin_44203158/article/details/109340113

Q:接口里面可以实现方法么?
A:是可以的!
从 Java8 之后添加了这个功能,主要考虑的是若接口发生变化,所有的实现类都要跟着进行修改。但有了接口可以实现方法后,就不用再改实现类了。
Q:接口中实现方法有 defaultstatic 两种修饰?
A:用 default 修饰的叫默认方法,用 static 修饰的叫静态方法。default可以被重写,但是 static不行。
Q:实现多个接口的默认方法冲突怎么办?
A:在实现类中重写,且可调用接口中默认的方法。
Q:那为什么不用抽象类?
A:抽象类不能多继承。

二)继承的类

AbstractMap 抽象类提供对 Map 接口的基本实现,以减轻实现 Map 接口的工作量。

对于不可变的 Map 实现类,只需要实现 entrySet() 方法。
对于可变的 Map 实现类,还需要实现 put()、remove() 等方法。

二、成员变量


    /**
     * 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;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

从变量和注释中能看出 HashMap 类的部分特性

  • 定义容量需要是 2 的次方数。因此表示的时候也用位运算来定义的
  • 默认负载达到 75% 时会扩容
  • 单个桶存的元素数大于 8 会变为树形存储,小于 6 改回列式存储
  • 当 capacity 大于 64 时,才会触发单节点的树形转换

容量为什么使用 2 的次方数?

在HashMap中采用的是除留余数法,即 table[hash % length]
在现代CPU中求余是最慢的操作,所以人们想到一种巧妙的方法来优化它,即length为2的指数幂时,hash % length = hash & (length-1)
如何做到的?
https://www.cnblogs.com/sanzao/p/10245212.html
https://blog.csdn.net/u014540814/article/details/88354793

// 下面的代码用于调整容量,将容量调为下一个 2 次方数
// 简单来说使用了位运算的方式,将这个数第一个 1 后面的所有位都换为 1
static final int tableSizeFor(int cap) {
  int n = cap - 1;
  n |= n >>> 1;
  n |= n >>> 2;
  n |= n >>> 4;
  n |= n >>> 8;
  n |= n >>> 16;
  return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

被标记为 transient 的变量

Q:transient 关键字是做什么的?
A:防止属性被序列化
Q:为什么要用 transient 修饰?
A:出于安全问题考虑

transient Node<K,V>[] table;

三、重要内部类

一)Node

最重要的内部类 Node,定义了 HashMap 中的节点。


    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    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;
        }
      // ......
    }

注意到使用了泛型类

https://segmentfault.com/a/1190000002646193
Q:什么是泛型类?
A:类名 + 一对尖括号。 person。在 JDK 5 中出现。
Q:为什么要用泛型类?
A:其中一个重要原因是为了创建容器类。假设没有泛型,为了支持不同类型的容器,可能需要定义多个类来支持。但有了泛型可以只用定义一个。减少了编码的冗余。
Q:泛型定义写在什么位置?
A:泛型类写到类名后面,泛型方法写到返回类型之前。
Q:泛型的类型是何时确定的?
A:应该是在编译时确定的。

有 4 个成员变量

final int hash;
final K key;
V value;
Node<K,V> next;

hashCode() 计算方式有些奇怪?

public final int hashCode() {
    return Objects.hashCode(key) ^ Objects.hashCode(value); // 为什么要用异或运算符?
}

四、重要函数

hash()

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

getNode()

这个里面体现了很多设计思想

  • first = tab[(n - 1) & hash] 从这里可以猜出来
    • hash 底层放到了一个数组里面
    • 容量设计为 2 的指数,在这里 n-1 二进制全是 1,方便做 & 运算
  • 在节点冲突时,会有两种检索冲突的方式。先判断是不是树节点,不是才顺序遍历
    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) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            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;
    }

putVal()

插入数据

  • 表的空容量判断
  • 桶上如果没有元素,直接新建
  • 桶上如果已有元素
    • 先判断 key 值是否存在,如果存在则将要替换 value
    • 如果是树结构,按照树的方式处理
    • 如果是列表结构,遍历看是否有 key 相同的
  • 若需要新建 Node 节点
    • 树转换的计数 + 1
    • table 存储量 + 1,若大于 threshold 则 resize()
    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;
    }

resize()

在扩容时会调用的函数

// 扩容时会按照 2 倍的方式扩容
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
         oldCap >= DEFAULT_INITIAL_CAPACITY)
    newThr = oldThr << 1; // double threshold

// 重新整理数据
for (int j = 0; j < oldCap; ++j) {
    Node<K,V> e;
    if ((e = oldTab[j]) != null) {
        oldTab[j] = null;
        if (e.next == null)
            // 如果该节点没有 hash 冲突,则放到原位或者2倍的位置
            newTab[e.hash & (newCap - 1)] = e;
        else if (e instanceof TreeNode)
            // 如果有 hash 冲突,且冲突很多(用树状存储),会进行拆分
            ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
        else { // preserve order
            // 有 hash 冲突,用列表存放,整体放到 [j + oldCap] 位置上
            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;
            }
        }
    }
}

treeifyBin()

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 如果 table 本身容量还很小,先使用扩容
        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 {
                // 其实是调用 LinkedHashMap 构造方法,TreeNode 也是 LinkedHashMap 扩展而来
                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);
        }
    }

后面函数大同小异,可自己探究。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值