首页 > 编程语言 >HashMap 源码解毒

HashMap 源码解毒

时间:2023-05-31 16:11:06浏览次数:29  
标签:Node hash HashMap next else 源码 key 解毒 null

PUT 方法解毒:


hashcode 高低16进行异或运算,尽量降低哈希冲突的概率
如果数组很小,hashcode的高位就不能被很好利用。

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为空或者长度为0,则需要初始化(默认大小16,默认扩容门槛0.75*16)
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 通过((n - 1) & hash)找到数组中合适的位子
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 如果数组中为空(数组中会存放Node链表或者红黑树) 新建Node节点
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果第一个节点的值等于插入的value
            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);
                        // 达到树化阈值进行树化
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 如果原来存在Node,是不是需要替换?onlyIfAbsent
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 大于阈值进行扩容  比如阈值是12 size==12,而不是modCount==12,时候扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
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倍旧容量
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 新阈值是旧阈值2倍
                newThr = oldThr << 1; // double threshold
        }
        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;
    }

标签:Node,hash,HashMap,next,else,源码,key,解毒,null
From: https://www.cnblogs.com/handsometaoa/p/17446346.html

相关文章

  • bitsandbytes通过源码安装后调用报错AttributeError: module 'bitsandbytes.nn' has n
    通过github下载的源码使用pipinstall-e.方式安装的时候会出现题目中的问题。这个时候先卸载掉bitsandbytes,然后重新使用pipinstallbitsandbytes安装,这种方式直接从仓库中安装,问题就解决了。目前尚不清楚问题出现原因,虽然两种方式的安装版本都是0.38.1......
  • 手机直播源码,android 轮播图(自定义组合控件)
    手机直播源码,android轮播图(自定义组合控件)1.项目gradle添加一下配置:  allprojects{ repositories{ ... maven{url'https://jitpack.io'} } } ​2.module中的gradle添加依赖:  dependencies{   implementation'com.github.truemi:SlideS......
  • 视频直播系统源码,Android 自定义底部导航栏
    视频直播系统源码,Android自定义底部导航栏添加依赖1.项目gradle添加一下配置:  allprojects{ repositories{ ... maven{url'https://jitpack.io'} } }   ​2.module中的gradle添加依赖:  dependencies{   implementation'com.github.tr......
  • lucene源码分析的一些资料
    针对lucene6.1较新的分析:http://46aae4d1e2371e4aa769798941cef698.devproxy.yunshipei.com/conansonic/article/details/51849659老的:AnnotatedLucene(源码剖析中文版)Lucene原理与代码分析完整版  ......
  • 【.NET源码解读】Configuration组件及自动更新
    Configuration组件是.NET中一个核心的、非常重要的组件。它提供了一种方便的机制,用于从配置文件、环境变量、命令行参数等各种数据源中读取和配置应用程序,以满足不同环境下应用程序的需求。在本篇文章中,将会介绍Configuration的基本用法,并通过源码探究.NET中Configuration的实现......
  • wukong引擎源码分析之索引——part 1 倒排列表本质是有序数组存储
    searcher.IndexDocument(0,types.DocumentIndexData{Content:"此次百度收购将成中国互联网最大并购"})engine.go中的源码实现://将文档加入索引////输入参数://docId标识文档编号,必须唯一//data见DocumentIndexData注释////注意://1.这个函数是线程安全......
  • BDB c++例子,从源码编译到运行
    第一步先下载源码,解压后./dist/configure--enable-cxx编译,然后make,makeinstall--enable-cxxTobuildtheBerkeleyDBC++API,enter--enable-cxxasanargumenttoconfigure. 默认的安装路径是:/usr/local/BerkeleyDB.6.1/ 代码如下:#include<stdlib.h>#include<strin......
  • 基于JAVA的springboot+vue学生综合测评系统,附源码+数据库+论文+PPT
    1、项目介绍本学生综合测评系统以springboot作为框架,b/s模式以及MySql作为后台运行的数据库,同时使用Tomcat用为系统的服务器。本系统主要包括首页,个人中心,学生管理,试题信息管理,测评试题管理,管理员管理,综合测评管理,系统管理,综合考试管理等功能,通过这些功能的实现基本能够满足日常......
  • springboot启动源码
    每个SpringBoot项目都有一个主程序启动类,在主程序启动类中有一个启动项目的main()方法,在该方法中通过执行SpringApplication.run()即可启动整个SpringBoot程序。问题:那么SpringApplication.run()方法到底是如何做到启动SpringBoot项目的呢?下面我们查看run()方法内部的源码,核......
  • UE4 源码解析----引擎初始化流程
      在研究UE4的源码过程中着实不理解的地方有很多,今天给大家分享一下UE4引擎的初始化流程。一、引擎的函数入口C++的函数入口都是Main()函数入口,UE4也是一样,Engine\Source\Runtime\Launch\PrivateWindows函数入口 引擎入口函数为:GuardedMain 二、引擎初始化的三个阶......