数据结构之HashMap1.8版本源码过程解析

HashMap源码过程解析

继承、实现关系

在这里插入图片描述

相关默认属性

  • 默认初始容量:16
  • 最大容量:1<<30
  • 加载因子:0.75f
  • 树化阈值:8
  • 树退化阈值:6
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;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;

类属性

  • table: 内部类Node的数组,是具体的存放容器
  • entrySet : Key值存放容器
  • size: 容器大小
  • modCount: 结构变化次数
  • threshold: 扩容阈值 = 加载因子*容器大小
  • loadFactor: 加载因子
    通过属性可以发现HashMap数据结构就是元素为Node的一个数组,Node是一个内部类,是一个链表的结构。当然jdk1.8之后,链表会转换为红黑树。
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
int threshold;
final float loadFactor;

链表结构

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}

红黑树结构

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;
    }

Hash算法

hash之后与hash值右移16位进行异或运算,这样就有高16位和低16位的信息,能够尽量减少hash冲突。
hash碰撞:如果两个输入串的hash函数的值一样,则称这两个串是一个碰撞(Collision)

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

添加元素流程

  • 选择插槽的方式 ,i = (n - 1) & hash
  • 插入数据为尾插法
  • 插入新数据完成后,会判断是否需要扩容
  • 具体代码分析,详情请看代码注释
  public V put(K key, V value) {
        return putVal(hash(key), key, value, 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;
        // 将tab引用指向 数据存放的容器
        // 如果容器为null进行扩容操作
        // 当然第一次扩容就是初始化容器过程,具体请查看扩容部分内容。 
        // 扩容返回的返回容器
        // n = tab.length 
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 此处选择要放入的插槽, 通过 (n - 1) & hash进行计算
        // 如果插槽当前为null,直接创建新的node
        // 同时p = tab[i = (n - 1) & hash])为后面链表遍历作准备
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
        	// 当插槽内已有数据,此时 p = tab[i = (n - 1) & hash])
            Node<K,V> e; K k;
            // k = p.key
            // 判断插槽第一个元素的Hash值是否和当前要加入的数据的hash值是否相等。
            // 判断当前元素的key 是否和当前数据的key是否相等,
            // 
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                // 将值 给临时变量 e
                e = p;
            
            else if (p instanceof TreeNode)
            	// 如果已经树化,使用树化添加的方法
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	// 链表遍历查询
            	// 结束情况,
            	// 1.当前节点没有Next节点,
            	// 2.当前节点 hash和key相等,也就是修改数据
                for (int binCount = 0; ; ++binCount) {
                	 // 下一个元素,赋值给e 
                	 // 此处看出是尾插法
                    if ((e = p.next) == null) {
   					// 1. 如果链表头节点是Null 创建 节点赋值给p的下一节点
                        p.next = newNode(hash, key, value, null);
                        // 判断是否需要树化
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        // 跳出循环
                        break;
                    }
                    // 如果 遍历到的当前节点值和添加值 hash值和key相等,修改结束循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 直接将e赋给p,继续往下遍历
                    p = e;
                }
            }
            // 如果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;
    }

扩容流程

第一次扩容
  1. 当 new HashMap 后并没有初始化容器Node<K,V>[] table
  2. 第一次添加元素时进行扩容
  3. 使用默认参数进行new Node<K,V>
第二次扩容
  1. 扩容时数据会分为高位 和低位,进行快速分配
  2. 无需重新计算数据位置,而是直接判断 (e.hash & oldCap) == 0
  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;
            }
            // 扩大为原来的2倍,  阈值也扩大为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
        // 第一次扩容,容器大小设置为默认值16,设置阈值为16*0.75 = 12
            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;
                // e = oldTab[j])
                // 不会空,就进行处理
                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
                    	// 因为 插槽算法e.hash & (newCap - 1) 
                    	// 当容器大小变化后,实际上只需判断新增的一位是0或者1,
                    	// 为0,数据位置不变,为1,数据位置变为+ newCap/2 位置
                    	// 二进制: 1111=16-1 》》 11111 =32 -1 
                    	// 低位
                        Node<K,V> loHead = null, loTail = null;
                        // 高位
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                        	// 将头节点的下个节点赋给next
                            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;
    }

树化流程

具体参见红黑树代码实现

删除数据流程

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
    }
    @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }
    
    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;
        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;
            // 查 满足的key
            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);
                }
            }
            // 进行remove操作
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                	// 如果是头节点
                    tab[index] = node.next;
                else
                	// 直接替换
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多多洛码代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值