/*
每一个key-value存储在Node<K,V>中,HashMap由Node<K,V>[]数
组组成。
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next; //hash:每个节点插入时先计算hash
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
} public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; } public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
} public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
} public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
HashMap常量与属性:
常量:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始化容量是16
static final int MAXIMUM_CAPACITY = 1 << 30;//数组的最大容量 2的30次方
static final float DEFAULT_LOAD_FACTOR = 0.75f; //默认加载因子 ,阈值=capacity*DEFAULT_LOAD_FACTOR
static final int TREEIFY_THRESHOLD = 8; //默认链表长度大于8时,链表转化成红黑数
static final int UNTREEIFY_THRESHOLD = 6; //默认元素个数小于6时,红黑数退化成链表
static final int MIN_TREEIFY_CAPACITY = 64;//在转变成树之前还会有一次判断,只有键值对数量大于64才会发生转换,
//这是为了避免在哈希表建立初期,多个键值对恰好被放入同一个链表中导致不必要的转化 属性:

transient Node<K,V>[] table;

transient Set<Map.Entry<K,V>> entrySet;

transient int size;

transient int modCount;//扩容次数

int threshold;//阈值,超过这个值就扩容

final float loadFactor; //加载因子

方法:

 static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value 
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

boolean evict) {//onlyIfAbsent==true:如果key值已存在,则不改变其value值
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//null或者长度为零,需要初始化大小,或者扩容
if ((p = tab[i = (n - 1) & hash]) == null) //(n - 1) & hash:确定index,因为n是2的次幂,n-1各进制位都为1,
// &:按位与 任何数与n-1做 &运算结果小于n-1,所以保证任何hash的下标都在n-1中
tab[i] = newNode(hash, key, value, null);//p==null表明:该下标的数组节点未被使用,直接赋值
else {//hash在 Node<K,V>[] 数组产生冲突,则在该节点的链表或红黑树查找
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//要插入的元素和冲突节点的第一个元素相等
e = p;//p:保存根据hash值找到的节点,e保存实时查找的最后一次找到的元素
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的后面
p.next = newNode(hash, key, value, null);
//元素个数大于8,链表转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
} //遍历到了key相等的元素,退出遍历
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;//e=p.next;p=e;往后遍历
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)//判断是否赋值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//添加元素,modCount++
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;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)//容量2倍,阈值2倍,
newThr = oldThr << 1; // double threshold
}
//oldCap>=0&& oldThr>0
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;
}

HashMap源码解析(简单易懂)的更多相关文章

  1. 【转】Java HashMap 源码解析(好文章)

    ­ .fluid-width-video-wrapper { width: 100%; position: relative; padding: 0; } .fluid-width-video-wra ...

  2. HashMap源码解析 非原创

    Stack过时的类,使用Deque重新实现. HashCode和equals的关系 HashCode为hash码,用于散列数组中的存储时HashMap进行散列映射. equals方法适用于比较两个对象 ...

  3. Java中的容器(集合)之HashMap源码解析

    1.HashMap源码解析(JDK8) 基础原理: 对比上一篇<Java中的容器(集合)之ArrayList源码解析>而言,本篇只解析HashMap常用的核心方法的源码. HashMap是 ...

  4. 最全的HashMap源码解析!

    HashMap源码解析 HashMap采用键值对形式的存储结构,每个key对应唯一的value,查询和修改的速度很快,能到到O(1)的平均复杂度.他是非线程安全的,且不能保证元素的存储顺序. 他的关系 ...

  5. HashMap源码解析和设计解读

    HashMap源码解析 ​ 想要理解HashMap底层数据的存储形式,底层原理,最好的形式就是读它的源码,但是说实话,源码的注释说明全是英文,英文不是非常好的朋友读起来真的非常吃力,我基本上看了差不多 ...

  6. 详解HashMap源码解析(下)

    上文详解HashMap源码解析(上)介绍了HashMap整体介绍了一下数据结构,主要属性字段,获取数组的索引下标,以及几个构造方法.本文重点讲解元素的添加.查找.扩容等主要方法. 添加元素 put(K ...

  7. 给jdk写注释系列之jdk1.6容器(4)-HashMap源码解析

    前面了解了jdk容器中的两种List,回忆一下怎么从list中取值(也就是做查询),是通过index索引位置对不对,由于存入list的元素时安装插入顺序存储的,所以index索引也就是插入的次序. M ...

  8. 【Java深入研究】9、HashMap源码解析(jdk 1.8)

    一.HashMap概述 HashMap是常用的Java集合之一,是基于哈希表的Map接口的实现.与HashTable主要区别为不支持同步和允许null作为key和value.由于HashMap不是线程 ...

  9. HashMap 源码解析(一)之使用、构造以及计算容量

    目录 简介 集合和映射 HashMap 特点 使用 构造 相关属性 构造方法 tableSizeFor 函数 一般的算法(效率低, 不值得借鉴) tableSizeFor 函数算法 效率比较 tabl ...

  10. 一、基础篇--1.2Java集合-HashMap源码解析

    https://www.cnblogs.com/chengxiao/p/6059914.html  散列表 哈希表是根据关键码值而直接进行访问的数据结构.也就是说,它能通过把关键码值映射到表中的一个位 ...

随机推荐

  1. maven配置及使用

    配置maven工程.从官网下载maven工具,然后解压到磁盘某个目录下即可. 计算机->属性->高级系统设置->环境变量. 新建如下变量: 变量名:MAVEN_HOME 变量值:C: ...

  2. java使用格式String型转成Date型

    public class TimeTwo { public static void main(String[] args) throws ParseException{ String s = &quo ...

  3. Python爬取qq空间说说

    #coding:utf-8 #!/usr/bin/python3 from selenium import webdriver import time import re import importl ...

  4. 面向对象编程思想(OOP)

    本文我将从面向对象编程思想是如何解决软件开发中各种疑难问题的角度,来讲述我们面向对象编程思想的理解,梳理面向对象四大基本特性.七大设计原则和23种设计模式之间的关系. 软件开发中疑难问题: 软件复杂庞 ...

  5. 关于基于LinphoneSDK通话项目开发中遇到的相关问题

    在之前小学期的项目开发当中,我们小组进行的是使用网上开源的LinphoneSDK来开发一款Android端的VOIP电话APP. 因为网上关于这个SDK在安卓端的开发文档相当少,所以我们只能根据少量的 ...

  6. union、union all 、distinct的区别和用途

    1.从用途上讲 它们都具有去重的效果 2.从效率上讲 distinct通常不建议使用,效率较低;union all 和union 而言,union all效率更高;原因是:union 相当于多表查询出 ...

  7. 简单hibernate框架测试

    -jar包 -日志配置文件: -实体类: package cn.itcast.domain; public class Customer { private Long cust_id; //客户编号 ...

  8. 第4次作业 -- 基于Jenkins的持续集成

    Jenkins 配置使用心得 先在 https://jenkins.io/download/ 下载Jenkins 下载之后安装,在指定的地方找到了初始密码,安装了一些插件之后,Jenkins就可以使用 ...

  9. impala和kudu使用的小细节

    七堇年:我们要有最朴素的生活与最遥远的梦想 . 即使明日天寒地冻,路远马亡.   加油! 之前入门的小错误总结,建表都会出错,真的好尴尬 还是要做好笔记 第一个错误: error:AnalysisEx ...

  10. shiro三连斩之第二斩(SSM)

    在SSM框架中使用shiro.环境 使用idea工具. 最主要的大概是配置文件如何配置吧. 1配置maven依赖 <?xml version="1.0" encoding=& ...