jdk1.8 HashMap源码解读
程序员文章站
2022-06-04 18:54:13
...
HashMap继承关系
HashMap几个关键常量
//默认初始化数量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树节节点阈值
static final int TREEIFY_THRESHOLD = 8;
//tree调整大小最大数
static final int UNTREEIFY_THRESHOLD = 6;
//树节点容量
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap 构造方法
1. 无参构造
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
当不指定初始化容量时,可以看出初始化为 16x0.75
2. 有参构造
2.1 指定初始容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
可以看出,我们可以自定义初始容量,默认加载因子为0.75
2.2 指定初始容量、加载因子
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
这里其实也就是做一些判断,进行一些异常处理
HashMap.put
下面我们看一下核心的put方法,看懂了put();其他的putAll();也是一样的
1. put()解析
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这里很简单,将我传入的K,V进行存储;这里包含了两个方法:putVal()、hash();
我们先看hash(),在看putVal()
2. hash()解析
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这里不难看出,HashMap是可以存储K为null的数据,这里进行了位移运算,计算出每一个hash值,这里就看出了hashCode()方法的重要性了,关于位移运算有兴趣的可以研究,知道hash返回int即可;
但是这里引申出一个问题,如果hash冲突怎么办?是直接替换value吗?
答案是不会替换,这是面试加分项,哈哈,这与HashMap的存储模式有关系,下面会说到!
3. putVal()解析
这是核心部分
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是否为null,或者长度等于0,如果是则调用resize()方法进行初始化
//而resize()内有调用了上面提到的核心常量
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//这里是计算hash值,如果为空,就新增
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//对比p的hash与k的hash是否相同,如果相同就赋值e=p,代表p是我们找到的节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断p是否是TreeNode类型,如果是,则走putTreeVal()方法,红黑树查找
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;
}
}
//判断hash是否冲突,冲突则进行追加,而非覆盖
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //判断是否需要扩容
resize();
afterNodeInsertion(evict);
return null;
}
这里用到了Node<K,V> 那他是什么呢?这里不贴源码了,其实就是一个树
Jdk1.8后HashMap的结果就变成里数据+链表+树的结构,这里就回答了上面的问题,hash冲突时,不会直接替换,而是在链表内在加一个挂载点进行处理存储
4.resize()解析
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) {
//如果oldCap大于最大容量值
if (oldCap >= MAXIMUM_CAPACITY) {
//则将threshold 赋值为Integer最大值
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
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;
//下边基本就是赋值,清空Node,对比hash值等操作
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交流群
上一篇: b b3-propagation协议
下一篇: layui中table表头样式修改方法
推荐阅读
-
PHP网页游戏学习之Xnova(ogame)源码解读(十四)_PHP
-
Java之HashMap源码分析(第五篇:访问元素)
-
PHP网页游戏学习之Xnova(ogame)源码解读(十二)_PHP教程
-
PHP网页游戏学习之Xnova(ogame)源码解读(十四)
-
JDK源码分析-HashMap
-
PHP网页游戏学习之Xnova(ogame)源码解读(二)_PHP教程
-
PHP网页游戏学习之Xnova(ogame)源码解读(十六)_PHP教程
-
ArrayList源码解读
-
YYText源码解读-YYText同步/异步渲染流程(一)—UIView与CALayer
-
YYText源码解读-YYText同步/异步渲染流程(二)