HashMap流程图
HashMap源码
Hash源码主要关注4大点:
JDK 8 以后底层使用 数组+链表/红黑树
1、确定哈希桶数组索引位置
HashMap.hash ----> hashcode()
2、插入数据
HashMap.put()
3、扩容机制
resize()
4、红黑树
treeify()
step1:new HashMap()
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
//设置加载因子
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
step2:map.put(key,value)
/**
* 添加或修改值
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 获取hash值
*/
static final int hash(Object key) {
int h;
/**
* 按位异或运算(^):两个数转为二进制,然后从高位开始比较,如果系统则为0,不同则为1
* h >>> 16:按无符号向右移动16位
* 扰动函数:(h = key.hashCode()) ^ (h >>> 16) 表示:
* 将key的哈希code一分为二,其中:
* 【高半区16位】数字不变。
* 【低半区16位】数据与高半区16为数据进行异或操作,以此来加大低位的随机性
* 注意:如果key的哈希code小于16位,那么是没有如何影响的,只有大于16位,才会触发扰动函数的执行效果
*/
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key key的hash值
* @param key the key key值
* @param value the value to put value值
* @param onlyIfAbsent if true, don't change existing value 如果是true,则不改变已存在的value值
* @param evict if false, the table is in creation mode.
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
//如果是空的table,那么默认初始化一个长度位16的Node数组
//初始化时table为空
if ((tab = table) == null || (n = tab.length) == 0){
//扩容table,并获取数组长度16
n = (tab = resize()).length;
}
//如果计算后的下标i,在tab数组中没有数据,那么则新增Node节点
//(n - 1) & hash --> 数组长度减一 & 哈希值(等同于 哈希值 mod n 取余)
if ((p = tab[i = (n - 1) & hash]) == null){
tab[i] = newNode(hash, key, value, null);
}else {//如果计算后的下标i在tab数组中已存在数据,则执行以下逻辑
Node<K,V> e; K k;
//如果与已存在的Node是相同的key值,则进行值覆盖
//校验与链表头节点是否匹配
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))){
e = p;
}else if (p instanceof TreeNode){
// 如果与已存在的Node是相同的key值,并且是树节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
}else {
//如果与已存在的Node是相同的key值,并且是普通节点,则循环遍历链式Node,并比对hash和key,如果都不相同,则新增节点
for (int binCount = 0; ; ++binCount) {
//如果链表只有头节点,则新增一个节点,并将链表后置指针指向新节点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//校验链表长度是否大于等于TREEIFY_THRESHOLD=8,是否需要转为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//若Node数组长度大于64则转为红黑树
treeifyBin(tab, hash);
break;
}
//判断是否为相同key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))){
break;
}
p = e;
}
}
//如果存在相同的key值
if (e != null) { // existing mapping for key
//记录key对应的旧值
V oldValue = e.value;
//判断是否允许覆盖
if (!onlyIfAbsent || oldValue == null){
//将key对应的value进行更新
e.value = value;
}
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* table扩容
*
* 常量命名解释:
* Tab=->Table 表
* Cap-->Capacity 容量
* Thr-->Threshold 阈值
*/
final Node<K,V>[] resize() {
//记录原table
Node<K,V>[] oldTab = table;
//记录原容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//记录原阈值
int oldThr = threshold;
int newCap, newThr = 0;
//第一步:根据情况,调整新table的容量newCap和阈值newThr
if (oldCap > 0) {
//如果老table的长度>= 1<< 30(2的30次方)
if (oldCap >= MAXIMUM_CAPACITY) {
//将阈值设置为1 << 31 -1
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果将老table的长度增长2倍作为新的容量长度(newCap),是否小于2^30并且 老table长度是否大于等于16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY){
//将新阈值增长为老阈值的2倍
newThr = oldThr << 1; // double threshold
}
}else if (oldThr > 0) {// initial capacity was placed in threshold
newCap = oldThr;
}else { // zero initial threshold signifies using defaults
//将新的容量设置为DEFAULT_INITIAL_CAPACITY=16
newCap = DEFAULT_INITIAL_CAPACITY;
//设置新的阈值,newCap * DEFAULT_LOAD_FACTOR(0.75)=12
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;
//第二步:根据neCap和newThr,构建新数组
//初始化新table
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//将新表赋值给全局变量的table
table = newTab;
//校验老table中是否有值,若有值在,则进行数据迁移
if (oldTab != null) {
//循环旧的Node数组
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
//将老table该节点设置为空
oldTab[j] = null;
//判断是否有后置节点,若没有说明e是最后一个节点
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 {
//获取oldTab数组下标的Node列表的下一个节点
next = e.next;
//计算e在老表oldTab的下标,如果是第一个Node,即:下标index==0
if ((e.hash & oldCap) == 0) {
if (loTail == null){
//将loHead指向oldTab数组第一个下标的第一个元素e
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;
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*
* Map 链表转红黑树
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//校验数组长度是否小于MIN_TREEIFY_CAPACITY=64
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY){
//数组长度小于MIN_TREEIFY_CAPACITY,进行扩容操作
resize();
}else if ((e = tab[index = (n - 1) & hash]) != null) {
//数组长度大于MIN_TREEIFY_CAPACITY,将链表转换为红黑树
TreeNode<K,V> hd = null, tl = null;
do {
//将Node转换为TreeNode
TreeNode<K,V> p = replacementTreeNode(e, null);
//将每个Node转换为TreeNode,用prev和next指针进行链接,并以hd为头节点
if (tl == null){
hd = p;
}else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
//如果头节点hd不为null,则进行树形化操作
if ((tab[index] = hd) != null){
hd.treeify(tab);
}
}
}
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*
* Map节点元素类(链表)
*/
static class Node<K,V> implements Map.Entry<K,V> {
//哈希值(数组下标)
final int hash;
//当前链表节点的key
final K key;
//当前链表节点的value
V value;
//链表后置节点指针
Node<K,V> next;
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;
}
}