HashMap源码解析

一 HashMap底层数据结构

HashMap底层数据结构为散列表,结合了数组和链表+红黑树 的优势,
在这里插入图片描述

Node数据结构 hash值为key的hash值,
在这里插入图片描述

二 HashMap的主要属性

//默认Hash表的大小
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
 //Hash表最大大小
 static final int MAXIMUM_CAPACITY = 1 << 30;
 //默认加载因子
 static final float DEFAULT_LOAD_FACTOR = 0.75f;
 //链表转换为红黑树的 链表长度,和hash表的大小
  static final int TREEIFY_THRESHOLD = 8;
   static final int MIN_TREEIFY_CAPACITY = 64;
  //红黑树转化为链表
  static final int UNTREEIFY_THRESHOLD = 6;


  //下面是第一次初始化的时候使用
  //散列数组
 transient Node<K,V>[] table;
 //hash表中存储的key-value对的大小
   transient int size;
   //散列表结构发生改变的次数
    transient int modCount;
   //扩容阈值,当你的哈希表中的元素超过阈值时,触发扩容
     int threshold;
     //加载因子
      final float loadFactor;

三 主要方法

计算key的hash值,这个地方将计算的hash值左移了16为,然后和hash值异或,为了使高16位也参与路由运算,减少了hash冲突

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

构造方法
参数 initialCapacity 初始化容量 loadFactor 加载因子
在构造函数中并没有对hash表经行初始化,在第一次添加数据的时候初始化
前面if判断 initialCapacity,initialCapacity的值必须大于等于0,且不能大于MAXIMUM_CAPACITY
loadFactor 不能小于等于0

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

tableSizeFor函数
对于输入的参数,返回一个大于等于当前值cap的一个数字,并且这个数字一定是2的次方数
比如 参数为 cap为9
n=8
0000 0000 0000 0000 0000 0000 0000 1000
| 0000 0000 0000 0000 0000 0000 0000 0100
0000 0000 0000 0000 0000 0000 0000 1100
| 0000 0000 0000 0000 0000 0000 0000 0011
0000 0000 0000 0000 0000 0000 0000 1111
| 0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 1111
| 0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 1111
return 15+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;
}

put方法,
hash key的哈希值,

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
  //tab引用当前的hashMap,p 表示当前散列表的元素
  //n  hashMap的长度   i key的路由寻址结果
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //延迟初始化逻辑,第一次调用putVal时会初始化hashMap对象中的最耗费内存的散列表
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;  // n赋值为散列表的数组的长度
        //case 1,当路由位置没有值的时候,也就是没有hash冲突的时候插入就好了
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
        //case 2 ,有hash冲突的时候
    else {
    //e 不为null的话,找到了一个与当前要插入的key-value一致的key的元素
    //k:表示一个临时的k
        Node<K,V> e; K k;
//case 2.1 当前桶中的元素,与你当前插入的key完全一致,后序看onlyifAbsent是否需要经行替换
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
//case 2.2 桶中的元素是红黑树,使用红黑树的插入算法
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//case 2.3 链表的情况,而且链表的头元素与我们要插入的key不一致的情况。
        else {
            for (int binCount = 0; ; ++binCount) {
//条件成立的话,说明迭代到最后一个元素了,也没找到一个与你要插入的key一致的node
//将要插入的元素加入到当前链表的结尾
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
  //当满足条件的时候,进行树化(不一定会树化)
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
         //条件成立的话,说明找到了相同key的node元素,需要进行替换操作
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //e不为空,找到一个和插入key完全一致的数据,需要进行替换
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            //返回之前的value值
            return oldValue;
        }
    }
    //插入node节点 ,modCount 表示散列表结构被修改的次数,替换Node元素的value不计数
  
    ++modCount;
    //插入新元素后,size自增如果自增后的值大于扩容阈值,则触发扩容。
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

put的流程图
在这里插入图片描述
扩容函数
为什么需要扩容?
为了解决哈希冲突导致的链化影响查询效率的问题,扩容会缓解该问题。

    final Node<K,V>[] resize() {
   // oldTab:  扩容前的哈希表
        Node<K,V>[] oldTab = table;
    //oldCa:扩容前的table数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
   //oldThr:扩容前的扩容阈值,触发本次扩容的阈值
        int oldThr = threshold;
        //newCap新的散列表的
        //newThr 扩容之后,下次再次触发扩容的条件
        int newCap, newThr = 0;
 //case 1 已经初始化过了,不是第一次扩容,
        if (oldCap > 0) {
// case 1.1 oldCap已经达到了最大值 则不扩容,且设置扩容条件为 int 最大值。
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
//case 1.2 newCap等于oldCap数组翻倍  newCap 小于数组最大值限制 且 扩容之前的阈值 >= 16
  这种情况下,则下一次扩容的阈值 等于当前阈值翻倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
 // case 2 oldCap == 0,说明hashMap中的散列表是null
 // 构造函数指定过oldThr
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
// oldCap=0 oldThr=0 
//调用的new HashMap();
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
 // newThr为零时,通过newCap和loadFactor计算出一个newThr
        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;
//hashMap本次扩容之前,table不为null
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
            //e 当前Node节点
                Node<K,V> e;
            //桶的当前位置不为空
                if ((e = oldTab[j]) != null) {
             //方便gc
                    oldTab[j] = null;
 //case 1 只有一个当前桶位有数据,从未发生过碰撞,这情况 直接计算出当前元素应存放在 新数组中的位置
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
 //case 2 是红黑树 
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//case 3 桶位已经形成链表
                    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;
    }

在这里插入图片描述

remove函数

    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        //tab 当前散列表的值
        // p当前node 元素
        //散列表数组的长度
        //index key路由后的位置
        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:查找到的结果
       // e:当前Node的下一个元素
            Node<K,V> node = null, e; K k; V v;
       //case 1 :当前通位中的元素为你要删除的元素
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
        //case 2 当前桶位置不仅是一个元素, 要么是红黑树 要么是链表
            else if ((e = p.next) != null) {
             //case 2.1 红黑树的情况
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
             //case 2.2 链表情况
                else {
                    do {
                    //链表中找到这个相同的key
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
           //   判断node不为空的话,说明按照key查找到需要删除的数据了
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //case 1 红黑树 说明需要进行树节点移除操作 
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                 //case 2 桶位元素即为查找结果,则将该元素的下一个元素放至桶位中  null
                else if (node == p) 
                    tab[index] = node.next;
                // 将当前元素p的下一个元素 设置成 要删除元素的 下一个元素。
                else
                    p.next = node.next;
                 //结构改变 modCount++
                // size--
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

get函数

    final Node<K,V> getNode(int hash, Object key) {
    //tab当前的哈希表
    // n哈希表的长度
    //first 桶位中的头元素 e:临时node元素
        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) {
            //case 1 桶中间第一个元素就是get的元素
            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;
    }
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值