HashMap源码解析(简单易懂)
/*
每一个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源码解析(简单易懂)的更多相关文章
- 【转】Java HashMap 源码解析(好文章)
.fluid-width-video-wrapper { width: 100%; position: relative; padding: 0; } .fluid-width-video-wra ...
- HashMap源码解析 非原创
Stack过时的类,使用Deque重新实现. HashCode和equals的关系 HashCode为hash码,用于散列数组中的存储时HashMap进行散列映射. equals方法适用于比较两个对象 ...
- Java中的容器(集合)之HashMap源码解析
1.HashMap源码解析(JDK8) 基础原理: 对比上一篇<Java中的容器(集合)之ArrayList源码解析>而言,本篇只解析HashMap常用的核心方法的源码. HashMap是 ...
- 最全的HashMap源码解析!
HashMap源码解析 HashMap采用键值对形式的存储结构,每个key对应唯一的value,查询和修改的速度很快,能到到O(1)的平均复杂度.他是非线程安全的,且不能保证元素的存储顺序. 他的关系 ...
- HashMap源码解析和设计解读
HashMap源码解析 想要理解HashMap底层数据的存储形式,底层原理,最好的形式就是读它的源码,但是说实话,源码的注释说明全是英文,英文不是非常好的朋友读起来真的非常吃力,我基本上看了差不多 ...
- 详解HashMap源码解析(下)
上文详解HashMap源码解析(上)介绍了HashMap整体介绍了一下数据结构,主要属性字段,获取数组的索引下标,以及几个构造方法.本文重点讲解元素的添加.查找.扩容等主要方法. 添加元素 put(K ...
- 给jdk写注释系列之jdk1.6容器(4)-HashMap源码解析
前面了解了jdk容器中的两种List,回忆一下怎么从list中取值(也就是做查询),是通过index索引位置对不对,由于存入list的元素时安装插入顺序存储的,所以index索引也就是插入的次序. M ...
- 【Java深入研究】9、HashMap源码解析(jdk 1.8)
一.HashMap概述 HashMap是常用的Java集合之一,是基于哈希表的Map接口的实现.与HashTable主要区别为不支持同步和允许null作为key和value.由于HashMap不是线程 ...
- HashMap 源码解析(一)之使用、构造以及计算容量
目录 简介 集合和映射 HashMap 特点 使用 构造 相关属性 构造方法 tableSizeFor 函数 一般的算法(效率低, 不值得借鉴) tableSizeFor 函数算法 效率比较 tabl ...
- 一、基础篇--1.2Java集合-HashMap源码解析
https://www.cnblogs.com/chengxiao/p/6059914.html 散列表 哈希表是根据关键码值而直接进行访问的数据结构.也就是说,它能通过把关键码值映射到表中的一个位 ...
随机推荐
- Android直接用手机打包apk!
你没有看错,用手机浏览器访问Jenkins,就可以打包apk,并生成下载二维码,发送邮件通知测试人员下载,从此解放双手,告别打包测试.先上本人手机邮箱收到的打包成功通知效果图: 废话少说, ...
- Python-接口自动化(八)
unittest单元测试框架(八) (九)unittest 1.基本概念 python自带的unittest单元测试框架不仅可以适用于单元测试,也适用于WEB自动化测试用例的开发与执行,uint ...
- PHP多进程的实际处理
多进程应用大批量的数据是非常舒服的一件事情. 处理之前理解两个概念:孤儿进程和僵尸进程 孤儿进程: 是指父进程在fork出子进程后,自己先完了.这个问题很尴尬,因为子进程从此变得无依无靠.无家可归,变 ...
- 【webpack学习笔记】a03-管理输出
webpack 中输出管理主要运用了两个插件: html-webpack-plugin clean-webpack-plugin 这两个插件可以满足常规的输出管理需求. html-webpack-pl ...
- JS案例六_2:省市级联动
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- java后台常用json解析工具问题小结
若排版紊乱可查看我的个人博客原文地址 java后台常用json解析工具问题小结 这里不细究造成这些问题的底层原因,只是单纯的描述我碰到的问题及对应的解决方法 jackson将java对象转json字符 ...
- 如何用css实现一个三角形?
昨天被人问到说如何用css实现一个三角形?em.... 当时被问到了,汗颜,今天找了一些帖子看了一下,也算是记录一下吧 代码如下: 实现效果:
- while循环与 for循环
import turtle turtle.setup(600,400,0,0) turtle.bgcolor('red') turtle.color('yellow') turtle.fillcolo ...
- Exploit-Exercises nebule 旅行日志(四)
接着上次的路程继续在ubuntu下对漏洞的探索练习,这次是level03了 先看下level03的问题描述: 精炼下问题,在/home/flag03的目录下有个crontab的文件是每分钟都在执行 这 ...
- el和jstl标签库讲解视频
https://www.bilibili.com/video/av22415283/?p=1