不论在面试题中还是在我们业务代码中hashmap这一容器的出场率是非常高,那么它的底层是怎么实现的?jdk1.7和jdk1.8两者实现方式有什么不同呢?当我们调用put(key,value)时,hashmap到底是怎么保存数据的?它为何能做到get(key) 的时间复杂度为O(1)的?
在JDK1.7中,HashMap采用位桶+链表实现,同一hash值的链表都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低(相对于在链表中查询数据)。而JDK1.8中,HashMap采用位桶+链表+红黑树实现,当存储的链表长度超过阈值(8)时,将链表转换为红黑树。链表查询的效率为O(n),红黑树的查询效率为O(logn)
1:当我们调用put(key,value) 时发生了什么:
源码分析:
1.1:有几个属性贯穿整个hashmap运行过程
transient Node<K,V>[] table; //数组 位桶
transient Set<Map.Entry<K,V>> entrySet; //
transient int size; 记录整个map的目前存放数据总大小
transient int modCount;
int threshold; //记录扩容值 当达到此值时触发hashmap扩容
final float loadFactor; //扩容阀值 默认为0.75
1.2:查看put源码:
public V put(K key, V value) {
//hash(key)方法调用key的hashCode方法来计算出hashcode值。
return putVal(hash(key), key, value, false, true);
}
//hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
*put元素的过程
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab用于存储key的hashcode相同的多个Node(位桶)
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//初始化新的位桶 大小与指定大小相同 默认为16
n = (tab = resize()).length;
//i = (n - 1) & hash 计算该hash值在位桶中的位置是否已存在Node 并赋值中间变量p
//这里计算table下标的说话(n - 1) & hash 可以保存计算出来的值是在table 数组的索引
if ((p = tab[i = (n - 1) & hash]) == null)
//不存在创建node 并写入容器中
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果当前key hash值对应存在Node对象 记录该节点 赋于中间变量e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
//如果当前节点结构变为红黑树结构(链表的长度大于阀值默认为(8)) 将值写入到红黑树中 如果key已存在 则返回原节点赋值e 如果没key存在返回null
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//如果不是 则认为时当前链表的长度小于转换阀值默认为(8) 则追加写入到链表中
//循环迭代链表 将value追加到最后
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//链表节点p的下一节点如果不存在 新生成node节点追加到链表的下一位
p.next = newNode(hash, key, value, null);
//如果循环次数大于等于转换tree阀值 将链表结构变更为tree结构
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
//退出循环
break;
}
//判断是否key的equals()为true 记录该节点并结束循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果中间变量e存在 代表该key在map中值已存在需要重新覆盖
if (e != null) {
V oldValue = e.value;
// onlyIfAbsent 如果为true如果即使key已存在也不进行变更 默认put方法此值为false
if (!onlyIfAbsent || oldValue == null)
//覆盖旧值
e.value = value;
//当map为LinkedHashMap 才执行
afterNodeAccess(e);
//返回旧值
return oldValue;
}
}
++modCount;
//如果目前容器的值要大于扩容阀值 触发扩容 顺便记录下map中值
if (++size > threshold)
resize();
//当map为LinkedHashMap 才执行
afterNodeInsertion(evict);
return null;
}
1.3:扩容方法(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>0代表此次为扩容
if (oldCap >= MAXIMUM_CAPACITY) { //如果oldCap>最大值 1 << 30 即2的30次方 则无法扩容
threshold = Integer.MAX_VALUE;//设置阀值为int最大值
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//如果oldCap的2倍小于最大值 并且oldCap大于默认初始化值将新阀值的大小扩一倍
newThr = oldThr << 1;
}
else if (oldThr > 0)
newCap = oldThr;// 初始容量设置为阈值
else {
//赋予默认容器大小(16) 已经默认阀值大小(16*0.75=12)
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) { //开始对数据进行数组copy
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null) //链表长度等于1的数据链表copy
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//为节点为红黑树数据copy
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 对链表长度超过1为链表copy
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;
}
1.4:链表长度超过8位转红黑树结构putTreeVa(...)源码分析:
/**
*
* 链表长度超过8位转红黑树结构
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
//将node节点变更为TreeNode
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
/**
*元素写入到红黑树中 这里涉及红黑树的数据写入较复杂需要对红黑树算法有一定了解
*后续在算法那章详细描述
*
*/
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
1.5:Node<K,V>对象源码
static class Node<K,V> implements Map.Entry<K,V> {
//key计算出hash值
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;
}
//判断两node点是否相同
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;
}
}
1.6:红黑树源码(后续会对红黑树算法进行分析)
/**
*
*红黑数算法结构
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
//记录父节点
TreeNode<K,V> parent; // red-black tree links
//数-左分支
TreeNode<K,V> left;
//数-右分支
TreeNode<K,V> right;
//数记录上一个点
TreeNode<K,V> prev; // needed to unlink next upon deletion
//判断该节点是否时红
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* 返回包含此节点的树 root节点
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
对红黑树节点的各式操作包含增删改查。。。。。
}
2:当我们调用get(key)时发生了什么
源码:
/**
*
*获取value
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* 根据key获取节点
*
* @param hash 通过key的hashcode方法获取
* @param key key值
* @return 返回节点或者null
*/
final Node<K,V> getNode(int hash, Object key) {
//定义临时变量位桶 tab first定义第一个遍历节点
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {//如果位桶中存在数据 计算该hash值所在位桶中位置 并取出赋予first
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//如果first的key 与需要查询的key相同 则直接返回
return first;
if ((e = first.next) != null) { //开始遍历链表
if (first instanceof TreeNode) //如果该节点已被转换为红黑树 从数中获取值
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//循环遍历链表 时间复杂度为O(n)
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}