Map之HashMap源码浅析-扩容

HashMap源码浅析

jdk11,工具idea

一、存储结构

入口:Ctrl+N查找到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;
    }

    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;
    }
}
复制代码

初始化时,为一个Node类型的数组,每个元素为一组键值对。

/**
 * 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.)
 */
transient Node<K,V>[] table;
复制代码

从静态类中的next可以看出,Node为链表结构。即Node数组的每个元素(也可称为桶)都可存储一个链表。

从 JDK 1.8 开始,一个桶存储的链表长度大于 8 时会将链表转换为红黑树

二、拉链法

1. 源码跟踪

示例:创建一个hashmap,放入3个键值对。

  1. 新建一个HashMap,默认大小为16,且都为2的幂。
/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
复制代码
  1. 将map中放入3个键值对。
@Test
public void testHashMapHashCode() {
    HashMap<String, String> map = new HashMap<>();
    map.put("K1", "V1"); // hash=2374
    map.put("K2", "V2");
    map.put("K3", "V3");
    System.out.println(map.get("K1").hashCode());
}
复制代码
2715
复制代码

存入map的键值的哈希值并不等于取出时的哈希值

  1. 确定桶的下表位置(即数组下标),跟踪put(k,v)源码:

存入K1,V1

public V put(K key, V value) { // K1,V1
    return putVal(hash(key), key, value, false, true);
}
复制代码
  1. 计算k1的hash=2374
static final int hash(Object key) { // k1
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    // hash=2374
}
复制代码
  1. put操作
// 参数=2374,k1,v1,false,true
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; // 16
    // 计算出桶的索引
    // 如果table的在(n-1)&hash的值是空,就新建一个节点插入在该位置
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null); // i=6
    // 冲突
    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);
                    // 如果冲突的节点数达到8个
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        // 如果tab为空或小于64-->resize()
                        // 大于64转为红黑树结构replacementTreeNode               
                        treeifyBin(tab, hash);
                    break;
                }
                // 如果有相同的key值就结束遍历
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 链表上有相同的key值
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 大于门限threshold (capacity * load factor)
    if (++size > threshold)
        resize(); // 扩容
    afterNodeInsertion(evict);
    return null;
}
复制代码
  • 后续操作很多源码从putVal展开

  • 注意索引的取值方法 i = (n - 1) & hash,表示该位置原来没有桶时,新链表的位置

  • K1,K2,K3存入的hash值分别为2374,2375,2376,对应的下标依次为6,7,8

2. put方法

2.1 头插法

当桶下标相同时,后一个put的KV对插在前一个KV对的前面,即新链表插在旧链表的头部。

步骤:

  • 计算K所在的桶下标

  • 确定桶后,在链表在顺序查找,时间复杂度与链表长度成正比。

2.2 null值

在计算hash值时,空值处理 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);即hashmap可以插入null值,但null没有hashCode()方法,就无法计算桶下标,因此以第0个桶确定为null的位置。

3. 扩容

如何理解算法时间复杂度的表示法

假设 HashMap 的 table 长度为 M,需要存储的键值对数量为 N,如果哈希函数满足均匀性的要求,那么每条链表的长度大约为 N/M,因此平均查找次数的复杂度为 O(N/M)。

为了降低复杂度,需要N/M尽可能大,因此M尽可能大。HashMap根据键(N)的数量动态调整table数组(M,Node<K,V>[] table)的长度,即动态扩容

满足++size > threshold条件时,进行扩容,调用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.
 */
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 旧表的两倍
    }
    // 旧表的长度的是0
    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;
}

复制代码
  • 扩容时须要拷贝旧表到新表,因此很耗时
  • 为提高扩容性能,处理碰撞,jdk1.8后,一个桶存储的链表长度大于 8 时会将链表转换为红黑树
/**
  * Replaces all linked nodes in bin at index for given hash unless
  * table is too small, in which case resizes instead.
  */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    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 {
            TreeNode<K,V> p = replacementTreeNode(e, null);
 ......

/**
 * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
 * extends Node) so can be used as extension of either regular or
 * linked node.
 */
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);
    }
....    

复制代码

源码阅读时,注释的作用明细,容易理解,基本给出了方法或类的作用概括,很有帮助。

转载于:https://juejin.im/post/5cb4867de51d456e311649b8

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值