HashMap 源码分析(JDK1.8)

最近在学习并发容器 ConcurrentHashMap,所以就先从 HashMap 开始了解。

前言

普及一下后面需要用到的一些知识:

  1. HashMap底层是由 数组+链表/红黑树 实现的;
  2. 这些数组就相当于哈希表;
  3. 哈希表简单理解:
    由对象的 hashCode 通过 hash 函数处理得到 hash 值,再处理 hash值 得到数组下标直接存储(时间复杂度为 O(1));
  4. HashMap hash函数的处理方式:
    用对象的 hashCode 高16位 和 低16位 作异或混合运算;
  5. 处理 hash值得到数组下标的方式:
    用 hash值对数组容量取模,得到数组下标;
  6. HashMap 大体数据结构示意图
    在这里插入图片描述

1.重要属性

/**
     * The default initial capacity - MUST be a power of two.
     * 默认数组容量为 16
     */
    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.
     * 默认负载因子 0.75
     */
    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.
     * 某个桶的链表结点个数大于等于 8 时,链表转为红黑树
     */
    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.
     * 某个桶的红黑树结点个数小于等于 6时,红黑树转为链表
     */
    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.
     * 在链表转红黑树之前,需要满足数组结点个数至少为 64,为了避免进行扩容、树形化选择的冲突
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     * 存放结点数组,数组大小必须为 2的幂
     */
    transient Node<K,V>[] table;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 如果数组结点个数 size > threshold,数组就需要扩容
     */
    int threshold;

    /**
     * 根据泊松分布得到
     * 用于与数组容量相乘计算的数组阈值
     */
    final float loadFactor;

2.重要内部类

2.1 Node

Node是最核心的内部类,它封装了 key-value 键值对,所有插入 HashMap 的数据都封装在这个对象里。

static class Node<K,V> implements Map.Entry<K,V> {
   
        final int hash;	// key的hash值
        final K key;	
        V value;
        Node<K,V> next; // 相同hash值的 Node

        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;
            if (o instanceof Map.Entry) {
   
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
2.2 TreeNode

红黑树结点,当链表长度过长的时候,会将 Node 转换为 TreeNode。这个类大概写了500多行代码比较复杂,这里就不着重分析,简单说下类的成员变量。

static final class TreeNode<K,V>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值