当你往HashMap里面put时,你其实在干什么?

 /**
* 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) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
  // 如果key为空,调用putForNullKey进行处理
if (key == null)
return putForNullKey(value);
  //根据key来获得对应的hash值
int hash = hash(key);
  // 搜索指定的hash值在对应的表中的索引
int i = indexFor(hash, table.length);
  // 如果 i 索引处的 Entry 不为 null,通过循环不断遍历 e 元素的下一个元素
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
  // 当entry的hash与上面获得的key的hash相等,并且entry的key与上面的key相等(==或者equals),把value赋值给oldValue
         //这里有个问题:当 Hash 冲突严重时,在桶上形成的链表会变的越来越长,这样在查询时的效率就会越来越低;时间复杂度为 O(N)
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
} modCount++;
// 如果 i 索引处的 Entry 为 null,表明此处还没有 Entry
// 将 key、value 添加到 i 索引处,并去创建一个entry
addEntry(hash, key, value, i);
return null;
}

根据上面 put 方法的源代码可以看出,当程序试图将一个 key-value 对放入 HashMap 中时,程序首先根据该 key 的 hash() 返回值决定该 Entry 的存储位置:如果两个 Entry 的 key 的 hash() 返回值相同,那它们的存储位置相同。如果这两个 Entry 的 key 通过 equals 比较返回 true,新添加 Entry 的 value 将覆盖集合中原有 Entry 的 value,但 key 不会覆盖。如果这两个 Entry 的 key 通过 equals 比较返回 false,新添加的 Entry 将与集合中原有 Entry 形成 Entry 链,而且新添加的 Entry 位于 Entry 链的头部——具体说明继续看 addEntry() 方法的说明。

当向 HashMap 中添加 key-value 对,由其 key 的 hashCode() 返回值决定该 key-value 对(就是 Entry 对象)的存储位置。当两个 Entry 对象的 key 的 hashCode() 返回值相同时,将由 key 通过 eqauls() 比较值决定是采用覆盖行为(返回 true),还是产生 Entry 链(返回 false)

上面程序中使用的 table 其实就是一个普通数组,每个数组都有一个固定的长度,这个数组的长度就是 HashMap 的容量。HashMap 包含如下几个构造器:

  • HashMap():构建一个初始容量为 16,负载因子为 0.75 的 HashMap。
  • HashMap(int initialCapacity):构建一个初始容量为 initialCapacity,负载因子为 0.75 的 HashMap。
  • HashMap(int initialCapacity, float loadFactor):以指定初始容量、指定的负载因子创建一个 HashMap。
 /**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
//如果key-value组成的entry数量超过极限,并且table的bucketIndex索引处不为空
if ((size >= threshold) && (null != table[bucketIndex])) {
  //把table的长度扩大到原来的两倍
resize(2 * table.length);
  //key == null的hash永远是0,如果key不为null,则会重新hash,并重新定位Entry在table中的位置
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
} // 获取指定 bucketIndex 索引处的 Entry
// 将新创建的 Entry 放入 bucketIndex 索引处,并让新的 Entry 指向原来的 Entry
createEntry(hash, key, value, bucketIndex);
}
 /**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}

JavaSE_坚持读源码_HashMap对象_put_Java1.7的更多相关文章

  1. JavaSE_坚持读源码_HashMap对象_get_Java1.7

    当你从HashMap里面get时,你其实在干什么? /** * Returns the value to which the specified key is mapped, * or {@code ...

  2. JavaSE_坚持读源码_ClassLoader对象_Java1.7

    ClassLoader java.lang public abstract class ClassLoader extends Object //类加载器的责任就是加载类,说了跟没说一样 A clas ...

  3. JavaSE_坚持读源码_Class对象_Java1.7

    Java程序在运行时,Java运行时系统一直对所有的对象进行所谓的运行时类型标识.这项信息纪录了每个对象所属的类.虚拟机通常使用运行时类型信息选准正确方法去执行,用来保存这些类型信息的类是Class类 ...

  4. JavaSE_坚持读源码_ArrayList对象_Java1.7

    底层的数组对象 /** * The array buffer into which the elements of the ArrayList are stored. * The capacity o ...

  5. JavaSE_坚持读源码_HashSet对象_Java1.7

    对于 HashSet 而言,它是基于 HashMap 实现的,HashSet 底层采用 HashMap 来保存所有元素,因此 HashSet 的实现比较简单,查看 HashSet 的源代码,可以看到如 ...

  6. JavaSE_坚持读源码_String对象_Java1.7

    /** * Compares this string to the specified object. The result is {@code * true} if and only if the ...

  7. JavaSE_坚持读源码_Object对象_Java1.7

    /** * Returns a hash code value for the object. This method is * supported for the benefit of hash t ...

  8. [一起读源码]走进C#并发队列ConcurrentQueue的内部世界

    决定从这篇文章开始,开一个读源码系列,不限制平台语言或工具,任何自己感兴趣的都会写.前几天碰到一个小问题又读了一遍ConcurrentQueue的源码,那就拿C#中比较常用的并发队列Concurren ...

  9. Java读源码之ReentrantLock(2)

    前言 本文是 ReentrantLock 源码的第二篇,第一篇主要介绍了公平锁非公平锁正常的加锁解锁流程,虽然表达能力有限不知道有没有讲清楚,本着不太监的原则,本文填补下第一篇中挖的坑. Java读源 ...

随机推荐

  1. 从身份证号码中获取性别、出生日期、籍贯,并更新mongodb

    有这样的需求,人员信息是存在mongodb中,需要存放人员的身份证.性别.出生日期.籍贯等信息.通过脚本导入这些信息,但是只导入了身份证号码,其他信息空缺.现在需要补全其他信息. 其实身份证信息就包含 ...

  2. Nginx 决策浏览器缓存是否有效

    expires指令是告诉浏览器过期时间 syntax:expires [modified] time; eopch | max | off; default : off context :http,s ...

  3. Linux(Centos)下调整分区大小(以home和根分区为例)

      在安装新系统的时候,有时候没法预估或者说错误的划分了分区大小,常常会导致我们后面的操作出现极大地不方便,比如某个分区分的太小了,导致 软件安装的时候会报安装空间不够,这就很麻烦.在这里我就记录一下 ...

  4. 图灵机器人API接口

    调用图灵API接口实现人机交互 流程一: 注册 图灵机器人官网: http://www.tuling123.com/ 第一步: 先注册, 然后创建机器人, 拿到一个32位的key 编码方式 UTF-8 ...

  5. 洛谷P1057传球游戏题解

    题目 这个题表面上看并不像DP,但是当我们看到方案数时,我们可能会想到什么??? 对,分类加法原理,在每一轮中,每一个点的方案数都要加上这个点左边的方案与右边的方案. 因此我们可以枚举,设一个DP数组 ...

  6. 【BZOJ3997】【TJOI2015】组合数学 Dilworth定理 DP

    题目描述 有一个\(n\times m\)的网格图,其中某些格子有财宝,每次从左上角出发,只能向下或右走.问至少走多少次才能将财宝捡完. 此对此问题变形,假设每个格子中有好多财宝,而每一次经过一个格子 ...

  7. LOJ2557. 「CTSC2018」组合数问题

    LOJ2557. 「CTSC2018」组合数问题 这道题是我第一道自己做完的题答题.考场上面我只拿了41分,完全没有经验.现在才发现其实掌握了大概的思路还是不难. 首先模拟退火,通过了1,2,6,9, ...

  8. Rainbond v5.1.2发布,微服务架构应用便捷管理和交付

    Rainbond v5.1.2发布,微服务架构应用便捷管理和交付 Rainbond是开源的企业应用云操作系统,支撑企业应用的开发.架构.交付和运维的全流程,通过无侵入架构,无缝衔接各类企业应用,底层资 ...

  9. Android平台如何获得屏幕尺寸?

    本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术,本文为大家讲解在Android平台上如何获得屏幕 ...

  10. 【BZOJ1568】[JSOI2008]Blue Mary开公司(李超线段树)

    [BZOJ1568][JSOI2008]Blue Mary开公司(李超线段树) 题面 BZOJ 洛谷 题解 是模板题啊. #include<iostream> #include<cs ...