JDK1.8HashMap分析
-HashMap是基于数组+链表+红黑树实现的一种数据结构,如下图所示
最上面的一部分是数组,下面是链表,当节点数>=8的时候,链表会自动转化成红黑树
在分析HashMap之前,我们先来看看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; 这个是负载因子,默认是0.75
- static final int TREEIFY_THRESHOLD = 8; 这个是树化的阈值,当链表节点>=8时,链表变成红黑树
- static final int UNTREEIFY_THRESHOLD = 6; 这个是反树化的阈值,当树的节点<=6时,红黑树变成链表
static final int MIN_TREEIFY_CAPACITY = 64; 这个是树化要求的最小容量,如果发生树化,但是数组长度<64则数组扩容
在这里需要补充一点,数组的长度只能为2的n次方,如何保证,下文有说明
然后介绍用到的变量
transient Node<K,V>[] table;//数组名为table
transient int size;//hashmap里面的元素数
int threshold;//所能容纳的key-value对极限,和table.length区分开
final float loadFactor;//负载因子 默认为0.75
然后是关键的几个数据结构
数组和链表都是用的这个数据结构
static class Node<K,V> implements Map.Entry<K,V> {
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()方法,把key和value的hash值做异或运算,得到的值作为Node的hash值,
//目的是让数据更分散,JDK1.8已经不用这种算法了
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;
}
}
下面是红黑树的节点结构,因为比较长,只截取了关键部分
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;
}
好了,了解了基础的结构之后,我们来看一下它是如何工作的
我们先来看一段很关键的代码,获得键的hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
仔细看这段代码,我们会发现他取了key的hash值记为h,然后把h向右位移16位,之后做亦或运算,用最后得到的值作为hash值,这段代码叫做搅动函数,目的是让数据在低位更随机,当然这段代码并不能直接使用,这只是一个数据准备
接下来是一段非常神奇的代码
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
这段代码的作用是返回大于输入参数且最近的2的整数次幂的数,是用来初始化threshold的,保证threshold为2的N次幂,具体的分析请看下面的这篇博客
http://www.bubuko.com/infodetail-1891723.html
接下来进入正题,看看HashMap是怎样对数据进行操作的
先来看新增操作put()
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果数组长度为空则扩容,并把长度赋值给n
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//(n - 1) & hash 核心代码,因为n为2的n次方,n-1化为2进制必然所有的位上全是1,比如n为16,那么
//n-1化为二进制则为1111,再与要插入值的hash值进行与运算,那么只有可能最低4位有值,通过这个算法
//保证了值一定位落在数组上
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);//如果为空就直接赋值
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//如果key相同则把赋值给e
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//如果是一个树节点 则把p转化成树节点赋值给e
else {
//遍历链表,如果找不到就在最后加一个新节点,当节点数>=7的时候把链表变成红黑树(这里的7不包含first节点),
//如果找到就把e赋值给p
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;
}
}
//如果最后p是新增,节点则p直接指向e,就不需要设置e的值,如果最后e是新增节点,则设置e的值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//如果size+1>容量则扩容
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) {
//如果原来数组长度>2^30 则把容量扩容到2^32-1,实际上数组不会扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//没有超过最大值就扩容2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
//初始容量设置为阈值
else if (oldThr > 0)
newCap = oldThr;
else { // 未设置初始大小则为默认值
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;
}
如何去取元素?
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
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值匹配的数组元素
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;
}
如何把链表变成红黑树?
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//规定只有当table.lenth>=64时才会进行树化,否则扩容
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 {
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);
}
}
因为红黑树不是本文的重点,所以涉及到红黑树的部分直接一笔带过了
如何进行删除?
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {//找到对应数组节点
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;//如果直接命中,则把node指向一个空节点
else if ((e = p.next) != null) {//节点下面有值,且未命中
if (p instanceof TreeNode)//如果p是TreeNode,则把p强转为TreeNode并且赋值给node
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {//如果找到了则把node指向删除节点,p指向删除节点的父节点
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//红黑树的删除逻辑
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//直接把node的下一个节点放到数组上去,实现删除
else if (node == p)
tab[index] = node.next;
//链表的删除逻辑
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
OK,这基本上就是HashMap的主线了,经过上面的学习,我想应该对于HashMap有了一个清楚的认识
我们来分析一下HashMap的性质
时间复杂度:
- 最理想情况下O(1),所有的值落在数组上,没有发生Hash碰撞
- 最坏的情况O(logN),就是一棵红黑树
HashMap是无序的,搜索修改的效率都非常高,但是是线程不安全的,如果对线程安全有一定的要求的话就需要程序员自己去实现,或者使用ConcurrentHashMap,如果要用有序的Map请使用TreeMap
如何对HashMap进行优化?容量是跟loadFactor有关的,负载因子越小则数组越小,hash碰撞的机遇就会越高,负载因子越大则数组越大,hash碰撞的机遇就会越小,优化HashMap其实就是权衡时间与空间的关系,是拿空间换时间还是拿时间换空间,其实默认值为0.75,是权衡时间复杂度与空间复杂度之后一个比较合适的值 一般不需要修改。
PS:第一次写博客,有不对的地方希望大神指出来,谢谢