JDK7 HashMap源码解析

简介: JDK7 HashMap源码解析

为什么HashMap中在链表与数组的选择时选择了数组?

因为使用链表的话访问查询会比较低(get方法),在ArrayList中可以直接使用下表来获取数据,但是链表需要一个位置一个位置遍历来查询。

在HashMap中get和put使用的频率都是非常的高的,所以我们也需要同时去保证他们的效率。

JDK 1.8 前 : 数组 + 链表


put方法:


● 通过 key 的 hashCode 经过 扰动函数(hash()) 处理过后得到 hash 值

● 通过 (n - 1) & hash (高效的求余数的办法,相当于)判断当前元素存放的位置(n 指的是数组的长度)

● 如果当前位置存在元素的话,就判断该元素与要存入的元素的 hash 值以及 key 是否相同

● 如果相同的话,直接覆盖,不相同就通过 拉链法 解决冲突

源码:


* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous(以前的) value associated with <tt>key</tt>, or
*         <tt>null</tt> if there was no mapping for <tt>key</tt>.
*         (A <tt>null</tt> return can also indicate that the map
*         previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
     // 如果table={}
    if (table == EMPTY_TABLE) {
     //初始化
        inflateTable(threshold);
    }
//查看key是否位null
    if (key == null)
        return putForNullKey(value);
//对key求hash
    int hash = hash(key);
     //Returns index for hash code h.
    int i = indexFor(hash, table.length);
//从第i个位置的table开始  该节点是否位null(是否是最后一个节点,是退出循环)   
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
       //hash值是否相等,key是否相等。如果不相等先取到旧值,再覆盖,最后将久值返回
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;//保存旧值
            e.value = value;//覆盖
            e.recordAccess(this);
            return oldValue;//返回久值
        }
    }
    modCount++;
    addEntry(hash, key, value, i);
    return null;
}


addEntry 方法


void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }
    createEntry(hash, key, value, bucketIndex);
}


createEntry方法


void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
//新建一个节点,并把它放到table的前面
      //创建新节点 Entry(int h, K k, V v, Entry<K,V> n)//Creates new entry.
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;
}
//  indexFor  根据hash值计算table中的i的大小
static int indexFor(int h, int length) {
    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
    return h & (length-1);
}

在put开头会先判断table={}是否成立,是则对hashmap进行初始化


The next size value at which to resize (capacity * load factor).
int threshold;
• 1
• 2


inflateTable方法


/**
 * Inflates the table.
 */
private void inflateTable(int toSize) {
    // Find a power of 2 >= toSize
    int capacity = roundUpToPowerOf2(toSize);
    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    table = new Entry[capacity];
    initHashSeedAsNeeded(capacity);
}


roundUpToPowerOf2 方法


//找到一个大于或等于number的2的幂
private static int roundUpToPowerOf2(int number) {
    // assert number >= 0 : "number must be non-negative";
        // number <=  1   , number = 1
      //    number > 1  时 :number是否是大于MAXIMUM_CAPACITY,如果大于MAXIMUM_CAPACITY那么容量就等于MAXIMUM_CAPACITY。如果小于那么就先number减1,然后翻倍在求翻倍后的小于等于参数的最大2的幂的值
    return number >= MAXIMUM_CAPACITY
            ? MAXIMUM_CAPACITY
            : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}


highestOneBit方法 (图解)


//获取小于等于参数的最大2的幂的值
public static int highestOneBit(int i) {
    // HD, Figure 3-1
    i |= (i >>  1);
    i |= (i >>  2);
    i |= (i >>  4);
    i |= (i >>  8);
    i |= (i >> 16);
    return i - (i >>> 1);
}


扩容:


addEntry方法


/**
 * The number of key-value mappings contained in this map.
 */
transient int size;//这个映射中包含的键值映射的数量
/**
 * The next size value at which to resize (capacity * load factor).
 * @serial
 */
// If table == EMPTY_TABLE then this is the initial capacity at which the
// table will be created when inflated. 
int threshold;//要调整大小的下一个大小值(容量负载因子) 16 * 0.75
void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }
    createEntry(hash, key, value, bucketIndex);
}


resize方法


void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }
     //new一个新对象 容量为newCapacity
    Entry[] newTable = new Entry[newCapacity];
//
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}


transfer方法


//Transfers all entries from current table to newTable.
void transfer(Entry[] newTable, boolean rehash) {
   int newCapacity = newTable.length;//新数组的容量
     // 遍历桶(table)
   for (Entry<K,V> e : table) {
       while(null != e) {
           Entry<K,V> next = e.next;
                      //rehash 
           if (rehash) {
                              //key 是否为空, 是 e.hash = 0 否 再hash
               e.hash = null == e.key ? 0 : hash(e.key);
           }
                     //算出新的数组下标
           int i = indexFor(e.hash, newCapacity);
                     //将当前的旧数组的下一个元素  指向 新数组中计算出来的对应元素中
           e.next = newTable[i];
             // 
           newTable[i] = e;
              //将next作为数组的头部
           e = next;
       }
   }
}


上面的扩容时,在单线程的时候是不会出问题的,但是在多线程的情况下,会出现死锁。


hash函数


final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }
    h ^= k.hashCode();
    // 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);
}


使用的是头插法:因为如果是尾插法需要从头部依次遍历找打最后一个元素进行插入(最后一个节点next==null),这样就需要花费时间遍历。所以1.7使用的是头插法。


get方法:


public V get(Object key) {
    if (key == null)
        return getForNullKey();
    Entry<K,V> entry = getEntry(key);
    return null == entry ? null : entry.getValue();
}


getForNullKey方法


private V getForNullKey() {
    if (size == 0) {
        return null;
    }
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null)
            return e.value;
    }
    return null;
}


getEntry方法


//获取节点
final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }
  // key ==null 返回0,否则返回key的hash值
    int hash = (key == null) ? 0 : hash(key);
    //计算楚下标,
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
//hash值相等并且key相等  那么e就是想找的节点
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}


注意: (n - 1) & hash 相当于 hash % n, (n - 1) & hash 是一种高效的求余数的办法。在默认容量16时,&操作只需要留下最后的4位,前面的都可以舍去。 因为比8更高位的都来自于8的2次幂,所以高位的1都是可以整除8,可以直接舍弃。(只有除数是2n才可以这样的操作)

0 0 0 0 0 0 0 0 0

256 128 64 32 16 8 4 2 1

直接&8的话是不行的,假设最后四位是1XXX,那么1XXX&1000=1000,很明显对8取余得到的结果不可能是8,余数应在0到除数减一之间,所以我们需要对&7,让取余结果最大在0-7之间。这就是为什么要&(2n-1)。

相关文章
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
1528 29
|
前端开发 数据安全/隐私保护 CDN
二次元聚合短视频解析去水印系统源码
二次元聚合短视频解析去水印系统源码
611 4
|
JavaScript 算法 前端开发
JS数组操作方法全景图,全网最全构建完整知识网络!js数组操作方法全集(实现筛选转换、随机排序洗牌算法、复杂数据处理统计等情景详解,附大量源码和易错点解析)
这些方法提供了对数组的全面操作,包括搜索、遍历、转换和聚合等。通过分为原地操作方法、非原地操作方法和其他方法便于您理解和记忆,并熟悉他们各自的使用方法与使用范围。详细的案例与进阶使用,方便您理解数组操作的底层原理。链式调用的几个案例,让您玩转数组操作。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
|
负载均衡 JavaScript 前端开发
分片上传技术全解析:原理、优势与应用(含简单实现源码)
分片上传通过将大文件分割成多个小的片段或块,然后并行或顺序地上传这些片段,从而提高上传效率和可靠性,特别适用于大文件的上传场景,尤其是在网络环境不佳时,分片上传能有效提高上传体验。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
安装JDK18没有JRE环境的解决办法
安装JDK18没有JRE环境的解决办法
1634 141
|
存储 Ubuntu 安全
在Ubuntu 16.04上安装openjdk-6/7/8-jdk的步骤
在整个安装过程中,你可能需要管理员权限,因此你可能要使用 `sudo` 来获取必要的权限。记得做完每一个步骤后,都要检查输出,以确保没有发生错误,并且每项操作都成功完成。如果在安装过程中遇到问题,查看 `/var/log/` 下的日志文件对于问题的解决可能是有帮助的。
754 21
|
IDE Ubuntu Java
在Ubuntu18.04安装兼容JDK 8的Eclipse集成开发环境的指南。
完成以上步骤后,您将在Ubuntu 18.04系统上成功安装并配置了Eclipse IDE,它将与JDK 8兼容,可以开始进行Java开发工作。如果遇到任何问题,请确保每一步骤都正确执行,并检查是否所有路径都与您的具体情况相匹配。
536 11
|
Java 关系型数据库 MySQL
在Linux平台上进行JDK、Tomcat、MySQL的安装并部署后端项目
现在,你可以通过访问http://Your_IP:Tomcat_Port/Your_Project访问你的项目了。如果一切顺利,你将看到那绚烂的胜利之光照耀在你的项目之上!
616 41
|
Oracle Java 关系型数据库
Tomcat和JDK的详细安装、下载和环境配置指南
以上就是JDK和Tomcat的下载、安装和环境配置的详细步骤。希望这个指南能帮助你顺利完成设置。
951 32
|
11月前
|
Ubuntu Java Android开发
在Ubuntu 18.04上安装与JDK 8兼容的Eclipse版本的步骤。
安装过程结束后,您就可以开始使用Eclipse来开发您的Java项目了,并且确保它与JDK 8兼容无误。这个过程涉及的是一个基本的安装流程,针对使用Java 8的用户,Eclipse的其他配置和插件安装根据个人开发环境和需求来定制。
598 0

推荐镜像

更多
  • DNS