JDK1.8:HashMap 源码学习
初学的时候 只知道其中的方法怎么用,并不太了解其中的实现,所以呢,写篇记录一下学习过程。
关于JDK 1.8 中的HashMap 相关面试题 会在后续新文章中分享 , 本文仅作为学习HashMap 源码记录
部分方法源码 持续更新中.......
目录
简单说说
对于JDK 1.8 中的HashMap 对比之前JDK 版本 相关的设计实现 ; 也是面试过程中的必问点,只知道方法的使用,是万万行不通的!!!!
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
// 继承 AbstractMap 实现了 Map ,Cloneable , Serializable 接口
}
属性
/**
* 简述为版本号
*/
private static final long serialVersionUID = 362498820763181265L;
/**
* 默认的初始化容量大小为16
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
/**
* 最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认负载因子
* 默认负载因子为0.75 是一个比较好的临界值;当负载因子过大,接近于1时,那么数组中的数据就越
* 多越密 ;当负载因子越小 ,接近于0时,数组中存放的数据也就是越少,越稀;简单来说 负载因子
* 的大小 控制着数组中数据的稀疏程度。
* 面试题:在这里,留个问题?为什么默认负载因子是0.75???
* 负载因子过大 会导致元素查找过程效率降低。过小,导致数组的数据越稀疏,利用率降低。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 当节点数大于 TREEIFY_THRESHOLD 则会转换成红黑树
* JDK1.8 亮点设计在于Hashmap 中的红黑树存储
*
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 当节点数小于 TREEIFY_THRESHOLD 则会转换成链表
*
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* bucket 进行树形化表的最小容量
* 如果表的容量太多,则会调整表的容量大小
*
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 用来存储元素的数组 长度2的幂次方
*/
transient Node<K,V>[] table;
/**
* 保存已缓存的元素集
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* 键值映射数(元素的个数) ,不等于数组的长度
*/
transient int size;
/**
* map 结构被修改的次数
*/
transient int modCount;
/**
* 超过临界值进行扩容;临界值(容量*负载因子)thredhold = loadfactor * capacity
* 当Size > threshold 进行扩容
*/
int threshold;
/**
* 负载因子
*/
final float loadFactor;
HshMap 中的Node节点
static class Node<K,V> implements Map.Entry<K,V> {
// hash 值
final int hash;
// 键、值
final K key;
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; }
// 重写 hashCode()
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
// 重写 equals()
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构造方法
/**
* 构造方法1 :指定 HashMap 初始化的容量大小 和 负载因子
**/
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);
}
/**
* 构造方法2 :指定 Hashmap 初始化容量大小
**/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 构造方法3 : 默认的构造方法 (用的最多的方法)
**/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* 构造方法4 :参数为一个Map
**/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
构造方法中调用的 putMapEntries()
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
// 获取此时元素个数
int s = m.size();
if (s > 0) {
// 如果此时数组table 为null
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
// 如果 此时计算出t 大于临界值
if (t > threshold)
threshold = tableSizeFor(t);
}
// 如果 此时获取map 的元素个数s > 临界值,调用resize() 方法实现扩容机制
else if (s > threshold)
resize();
// 将m 中的元素 遍历调用putVal() 添加到 HashMap 中
// putVal() 在介绍put() 方法会简述
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
put() 方法
// 提供的是put 方法 但是底层的实现的putVal() 方法 未提供公开使用
// 这地调用putVal() 的第一个参数:通过调用hash() 计算出键key 对象的hash 值(int)
// 第二个 第三个 参数 将key value 传过来
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 该方法的参数
* hash : key 的hash 值
* key : key
* value : 需要put 的目标值
* onlyIfAbsent : boolean 类型 如果为true 则不能修改已存在的值
* evict : 如果为false 则此时的table 数组 处于创建状态
**/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// 用来保存原表
Node<K,V>[] tab;
// 用来标记 下标值为hash 的节点
Node<K,V> p;
// n 用来标记 长度
int n, i;
// 如果 table 没有初始化(即为null) 或者 长度为0 ,则触发扩容机制
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 这里 要注意 是使用 (n - 1) & hash 来计算 目标元素放置到哪个bucket
// 若此时的bucket 为null 则新增节点放置该bucket 位置
// 这里是 bucket 中不存在元素的情况
if ((p = tab[i = (n - 1) & hash]) == null)
// 调用此方法 就会使当前下标为hash 的节点的元素为空,就会生成一个新节点放在该位置
tab[i] = newNode(hash, key, value, null);
// 这里是 bucket 中存在元素的情况
else {
Node<K,V> e; K k;
// 比较 节点 key 和 hash 值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 如果当前节点的hash 值 ,key 值 都相等 ,
// 并且因为此时的onlyIfAbsent 为false ,该值先存放到e 中,该节点的value 值会被改变
e = p;
// 判断是否为树节点
// 如果为树节点 那么就使用红黑树插入
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 如果为链表节点
else {
// bigCount 用来计数 节点数 ,在链表末尾插入节点 ,如果节点数大于临界值 则转换成红黑树
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// 如果该节点e.next 为空 就新增一个节点追加其后
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 插入到链表中的元素key 值如果与节点的key 值相等 执行break
// 遍历链表
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 相当于 p = p.next
p = e;
}
}
// 代表此时的要插入位置 已存在节点 (key 、hash 均相等)
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// 新值覆盖旧值
e.value = value;
// 回调 ,该方法是空方法 预留操作
afterNodeAccess(e);
// 返回旧值
return oldValue;
}
}
// hashmap 结构修改 则++
++modCount;
// 如果size 实际的元素个数 大于临界值 触发扩容机制
if (++size > threshold)
resize();
// 回调, 该方法是空方法 预留操作
afterNodeInsertion(evict);
// 最后 返回 null
return null;
}
get() 方法
// get()
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
// getNode()
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; // 记录表对象
Node<K,V> first, e; // 第一个节点、当前节点
int n; // 表的长度
K k;
// tab 不为空 并且 表长度大于0,并且对应的节点存在(key 对象的hash值计算得到下标 目标位置的节
// 点)
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 当前的节点 hash key 值 都符合 ,直接返回该节点
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 判断当前节点后的节点
if ((e = first.next) != null) {
// 从红黑树中获取
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 从链表中遍历获取
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
resize() 方法
final Node<K,V>[] resize() {
// oldTab 标记该对象
Node<K,V>[] oldTab = table;
// oldCap 为当前容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 阈值(容量*负载因子)
int oldThr = threshold;
// 声明新容量、新阈值
int newCap, newThr = 0;
// oldCap > 0 说明已经被初始化
if (oldCap > 0) {
// 判断是否超过了最大容量 ,超过了最大值,直接把最大值赋值为当前的阈值
// 并且返回旧数组
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 如果 没有超过最大容量
// 新容量 = 旧容量*2 , 并且没有超过最大容量,而且大于默认初始容量 ,
// 此时才会新阈值 = 旧阈值*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 如果oldCap <=0 ,数组未初始化
// oldThr >0 将旧阈值 赋值给新容量
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 这里的else 代表上述条件都不满足
// 代表着 tab为初始化,并且调用的默认构造器
// 将新容量 赋值为默认初始容量
// 阈值 赋值为 负载因子*初始容量
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 经过上述的分支 newCap 是一定不为Null ,但是如果为第二条件分支,那么newThr = 0
// 在此做一个操作 若到此当前的newThr = 0 ,容量*负载因子 通过计算得出newThr 值
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 计算得出的newThr 赋值给threshold
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;
}