HashMap 源码分析

HashMap 源码分析

原文地址:https://my.oschina.net/RyenAng/blog/4484655

HashMap 是一个散列表,采用 Key-value 键值对的形式存储数据。

HashMap 实现了 Map 接口,不能用于多线程同时更改更改数据的场景,是线程不安全的Key 和 Value 都可以是 null 值

  • 实现 Cloneable 接口,覆写其 clone() 方法,实现数组元素的克隆;
  • 实现 Serializable 接口,表示这可以系列化传输
  • 继承 AbstractMap

image-20200807163439965

1、HashMap 的结构

image-20200807184211467

在 HashMap 中采用拉链法解决 Hash 冲突,也就是通过数组和链表结合起来,如果遇到哈希冲突,就把新的 Node 添加到链表尾部即可。

在 HashMap 中,是根据 hash(key) & (table.length-1) 计算得到其在数组的 index,并通过比较 hash(key) 和 key 的值确定 Node,并把 Node.value 返回。

1.1、JDK 1.8 跟 JDK 1.7 的不同

  • 当链表的长度大于 8 而且 table 数组的长度大于 64 时,会把链表转换为红黑树,使用 treeifyBin(tab, hash); 方法。当数组 table 的长度小于 64 时,会优先使用 resize() 方法给 table 数组扩容。
  • hash() 计算函数的不同,JDK 1.8 效率更高。hash() 是扰动函数,避免了一些实现比较差的 hashCode() 方法,减少哈希碰撞

JDK 1.8

/** Hash 扰动函数 */
static final int hash(Object key) {
    int h;
    // hashCode() 对象原本的哈希值
    // ^ 按位异或运算
    // >>> 无符号位移
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

在 JDK 1.7 ,计算次数比较多,性能比较差

static int hash(int h) {
    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

HashMap 主要的成员变量:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    private static final long serialVersionUID = 362498820763181265L;
    // 默认容量 也就是 16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
    // 默认加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 当(bucket 桶)中的链表长度大于 8 会转为红黑树
    static final int TREEIFY_THRESHOLD = 8;
    // 当(bucket 桶)的链表长度小于 6 会转为链表
    static final int UNTREEIFY_THRESHOLD = 6;
    // bucket 桶中的链表要转为红黑树,对应 table 的最小大小
    // 也就是说,如果某个 bucket 桶的链表长度大于 8 了,如果 table 数组小于 64 
    // 会先对 table 数组扩容,减少冲突
    static final int MIN_TREEIFY_CAPACITY = 64;
    /** Hash 扰动函数 */
    static final int hash(Object key) {
        int h;
        // hashCode() 对象原本的哈希值
        // ^ 按位异或运算
        // >>> 无符号位移
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    /** 数组 table */
    transient Node<K,V>[] table;
    /** 存放具体元素的值,使用 Entry 遍历的时候 */
    transient Set<Map.Entry<K,V>> entrySet;
    // map 的元素个数
    transient int size;
    // 对 map 的修改次数
    transient int modCount;
    // 衡量数组是否要扩容的关键,threshold = capacity * loadFactor,
    // 当 size 大于这个数的时候,会对数组 table 进行扩容
    int threshold;
    // table 数组的加载因子
    final float loadFactor;
}
  • loadFactor 加载因子,默认 0.75f

给定的默认容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12 就需要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操作,所以非常消耗性能。

loadFactor加载因子是控制数组存放数据的疏密程度,loadFactor越趋近于1,那么 数组中存放的数据(entry)也就越多,也就越密,也就是会让链表的长度增加,loadFactor越小,也就是趋近于0,数组中存放的数据(entry)也就越少,也就越稀疏。

loadFactor太大导致查找元素效率低,太小导致数组的利用率低,存放的数据会很分散。loadFactor的默认值为0.75f是官方给出的一个比较好的临界值

  • threshold ,HashMap 中能放入元素的个数

threshold = capacity * loadFactor当 size>=threshold 的时候,那么就要考虑对数组的扩增了,也就是说,这个的意思就是 衡量数组是否需要扩增的一个标准

1.2、HashMap 链表 、 红黑树的类

Node 也就是链表状态时候使用的

/**
 * table 数组的数据结构 Node<K,V> 
 */
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash; // hash值
    final K key; // key value,可以不能被修改,value 可以
    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;
    }
    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }
    // 重写 hash code 的方法
    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }
    // 重写 equals 方法
    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;
    }
}

TreeNode 部分 ,用在平衡二叉树中

  • [ ] TODO : 手撕平衡二叉树、红黑树源码
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);
    }
}

2、HashMap 的构造方法

HashMap 主要有 4 个构造方法。HashMap 的容量并不会在构造的时候直接分配,而且在 put 方法第一次调用的时候分配。

为了提高运算效率,设定 HashMap 容量大小为 2 的 n 次方。计算落槽位置更快。《码出高效 P161》

落槽位置计算公式 hash(key) & (length - 1),length 是 table 数组的长度,也就是 HashMap 的容量大小。当 length 的长度等于 2 的幂次方的时候, hash(key) & (length - 1) = hash(key) % length因为位运算比较快,所以采用了 2 的幂次方

/**
 * 指定 容量 和 加载因子的构造方法
 */
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

/**
 * 指定容量的构造方法
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * 使用默认加载因子
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * 传入一个 map 的构造方法
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

putMapEntries 方法。

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    // map s 的大小
    int s = m.size();
    if (s > 0) {
        // 如果 table 还没有初始化
        if (table == null) { // pre-size
            // 计算 ft ,s 是 m 实际元素的大小
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            // 如果 t 大于 阈值,则重新计算阈值 ?不太理解这里
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        // 将 map 的元素放入 HashMap 
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

3、HashMap 的 put 和 get

3.1 HashMap 的 put() 方法

JDK 1.7 没有是否要转换为红黑树这一判断,JDK 1.7 采用的是头部插入的方式。

HashMap 插入逻辑图解:

image-20200807201626129

HashMap 插入源码。

// 公共方法,put 进元素
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
// 使用这个方法往 hashMap 中添加数据
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 如果 table数组 为空或者 table 的长度为 0
    if ((tab = table) == null || (n = tab.length) == 0)
        // 调用 resize 扩容
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 如果 table[i = (n - 1) & hash] 等于 null 直接将 node 放入 table中
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 如果 table 数组的第一个 Node 就要找放入元素的值,也就是 hash(key) 和 key 相等
        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 {
        // 如果是链表,循环遍历变量,binCount 是链表节点个数
            for (int binCount = 0; ; ++binCount) {
                // 为链表尾部插入,
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 如果链表长度大于 8 则使用 treeifyBin 转为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 如果找到有 hash(key) 和 key 相同的,直接退出循环
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            // 也就是以及存在 key 了,将 value 更新,然后返回 旧 value
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
                // 访问这个值后的操作
            afterNodeAccess(e);
            return oldValue;
        }
    }
    // 对 map 的结构有改动才 + 1
    ++modCount;
    // 判断是否需要扩容
    if (++size > threshold)
        resize();
   // 插入 node 后的操作
    afterNodeInsertion(evict);
    return null;
}

3.2 HashMap get() 方法

// 根据 Key 获取 Value,没有就返回 null
public V get(Object key) {
    Node<K,V> e;
    // 通过 hash(key) 和 key 找到 Node
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // table 不为 null,tab 的长度大于 0,table 数组对应的位置不为 null
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
            // 如果第一个 Node 就是要找的数据,直接返回,hash(key) 和 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) {
            // 如果是红黑树,则从树中找
            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;
}

4、HashMap 的扩容机制

HashMap 扩容的时候会默认扩容 2 倍,但扩容是非常耗时的操作,会把遍历 HashMap 中的所有元素,因此在使用 HashMap 要避免扩容。

/**
 * 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;
    if (oldCap > 0) {
        // 超过最大值就不再扩容了,不管 hash 碰撞了
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 没有超过最大值,就扩充为原来的 2 倍
        // newCap = oldCap << 1 表示新的容量等于旧的容量乘以 2 ,位移运算比较快
        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
        // 使用默认值,也就是 table 的长度为 0
        newCap = DEFAULT_INITIAL_CAPACITY;
        // capatcity 也就是 table 数组的容量,当插入元素 size 大于扩容阈值就会扩容
        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"})
    // 初始一个新的 table 数组
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    // 将旧的 table 中的内容移动到 新 的 table,每个元素都要重新计算,重新分配 hash 和位置。
    if (oldTab != null) {
        // 遍历旧的 table 数组
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // 如果只有一个 node,直接放入新的 tables 中
                // 为什么可以直接放入,扩容之后, 原本没有 hash 冲突,现在也不会有 hash 冲突
                // TODO 理解一下底层的原理
                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;
                        }
                        // 原来的索引 + OldoldCap
                        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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值