本博客目标在于对Map家族的源码做个尝试性的解析
HashMap的本质是数组加链表的形式
put的流程为:
1:根据传入的key值计算hash值,然后取右移16位之后的值与hashCode的值做异或运算得到数组下标的值:index
2:根据index的下标,获取bucket,如果bucket不冲突碰撞则直接放在Bucket中,如果碰撞了则放在内部的链表中,超过一定长度链表会转为红黑树
3:如果节点已经存在了,则替换,若长度超出了范围,则会调用resize
具体的源码:
首先是hash()
static final int hash(Object key) {
int h;
//先计算得到hashCode,然后将hashCode右移16位
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
为什么要低位移动16位这张图是最好理解的了
我们计算hash是为了获得在数组中的下标对应的bucket,也就意味着我们需要先得到index下标,n是鼠标容量-1,为什么要-1呢,因为在HashMap中有个方法:
/**
* Returns a power of two size for the given target capacity.
*/
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的倍数,也就意味着可以用&运算代替%运算,效率大大提升
这样通过(n-1)&hash 我们就可以获得了下标index:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果下标对应的bucket为空或者内部无元素
if ((tab = table) == null || (n = tab.length) == 0)
//则会重新为内部申请空间,请跳到下面,将具体如何分配空间
n = (tab = resize()).length;
//如果未发生碰撞,则直接将这个值赋值给这个bucket
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;
//如果第一个元素不相等,并且是红黑树类型的,则按红黑树添加的方法添加元素
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);
//如果长度超过了默认的设置的长度(8),则将链表转为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//在链表中判断hash和key是否与对应的相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//说明链表中存在值,抽到这里主要是为了防止写过多的相似的代码
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//modCount++ ,与最后会与预期的对比,从而保证安全
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize代码
final Node<K,V>[] resize() {
//既然会扩容,原先的配置都需要保存一份
//table是map中的属性,顾名思义 原先的table
Node<K,V>[] oldTab = table;
//原先的容量进行判断
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//threshold:扩容临界值,意味着达到最大容量将发生扩容,保存原先配置
int oldThr = threshold;
//新的容量和新的扩容临界值
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果容量已经达到的最大限度的一办,并且原先的容量已经超过了默认设置的大小值(即将达到默认的扩容临界值,因为默认的负载因子为0.75)
//则将新的扩容临界值增大一倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//说明table此时还是空的
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;
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)//说明只有单个元素,则从先计算hash然后重新计算下标,并且更改位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//如果是红黑树,则进行红黑树的复制
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
//否则,这里的代码有点看不懂,借鉴了其他[其他大神的看法](https://blog.csdn.net/login_sonata/article/details/76598675)
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;
}
Get操作:
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 &&
//判断下标对应的bucket是否存在
(first = tab[(n - 1) & hash]) != null) {
//判断相等的条件是:hashCode要先相同,然后判断特有的key是否相同
//因为hashCode相同并不意味着对象就相等
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//bucket中的值命中了则直接返回
return first;
//说明内部是一个链表或者RBTree
if ((e = first.next) != null) {
//如果是RBTree,则按RBTree的方式
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;
}
get总结:
1.算hash(高位右移16位后异或)
2.判断bucket[index]中的值是不是恰好是所求的值
3.判断是RBTree还是ListNode
4.各自的策略然后get元素
remove操作
/**
* Implements Map.remove and related methods
*
* @param hash hash for key 字面翻译:hash值
* @param key the key 唯一的key
* @param value the value to match if matchValue, else ignored 是需要key匹配就删除还是还得需要value也匹配
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing 删除节点之后其他节点是否需要移动
* @return the node, or null if none
*/
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;
//判断bucket的key是否刚好相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//为什么这里不直接删除然后返回呢,1是减少重复代码,2是可能还需要移动元素
else if ((e = p.next) != null) {
//是否是红黑树
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//遍历链表
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//说明找到了hash+key对应的节点
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
//remove的时候为了满足bst的平衡性会发生自旋操作
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
//modCount++ ,防止在全局获取size等方法的时候又其他线程也执行了操作
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
总结remove操作:跟get操作其实是相同的,但是难点其实在于红黑树的自旋操作,为了尽量满足平衡二叉树的特性(O(logN))
总结一下:
HashMap的存储结构:数组+链表+红黑树,当链表长度超过一定范围(默认值为8),则会将链表转为红黑树
HashMap中存储的都是Node节点(实现了Map.Entry)
而关于Java8 的ConcurrentHashMap
在7中ConcurrentHashMap是通过分段锁(segment来实现并发的)
在8中通过数组+cas+红黑树来实现并发
首先关于hash寻址,Java8中并没有多大的改进,还是通过hashCode高16位与数组长度-1做异或的方式获取下标
然后同步方式:
先获取下标对应的数组值,如果不为空则通过cas设置值
如果不为空则利用synchronized锁住然后修改值
并且因为内部的hash,key都是final类型,所以安全能够保证,value和next是volatile修饰,则可以保证一致性
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
this.next = next;
}
TreeMap:
数据结构:红黑树 ,几个重要的变量:root(根节点),size(节点个数),comparator(排序的关键)
TreeMap与HashMap的区别在于:TreeMap是排序的,那是如何保证顺序的呢
put源码:
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
//
compare(key, key); // type (and possibly null) check
//移动根节点到新插入的元素
root = new Entry<>(key, value, null);
size = 1;
//防止多线程遍历error
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
//判断是否存在相同元素
if (cpr != null) {
do {
//从根节点开始遍历
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
//小于说明在左子树
t = t.left;
else if (cmp > 0)
//否则右子树
t = t.right;
else
//说明2个值相等,然后返回旧的值
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
//key需要是COmparable的子类,所以让其自主排序
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
//小于0说明是小于,则左边存放小点的值
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
//此时parent处于大于|小于key的最小值|最大值处,将这个节点设置其父节点
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
put总结:put之前先遍历,按照排序算法找到最合适的位置,然后插入
当我们调用foreach keyset 然后getKey的时候会怎样呢:
for(Student student:treeMap.keySet())
{
treeMap.get(student);
}
引申一点,这段代码会被转换为:
for(Iterator<Map.Entry<Student, String>> it=treeMap.entrySet().iterator();it.hasNext();){}
所以如何遍历保证顺序在于iterator:
final Entry<K,V> nextEntry() {
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
next = successor(e);
lastReturned = e;
return e;
}
遍历时候的调用栈为:
next()<- nextEntry().value<-successor() 所以核心为successor()方法
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
if (t == null)
return null;
//中序遍历节点
else if (t.right != null) {
//遍历右边,取得右边的
Entry<K,V> p = t.right;
while (p.left != null)
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
2018-10-10 23:47
今天想手写lru的时候发现,数组初始化的时机,HashMap是第一put的时候才初始化的,emmm这种方式不错哦,用到的时候才初始化
LinkedHashMap
- LinkedHashMap适合于读少些多的场景,因为它的内部是带头结点的单向循环链表,既(有head和tail指针,插入非常块),读的话因为要从头到尾遍历因而缓慢
- HashMap适合于读多写少的场景,push的时候无论是RBTree还是list都要设计到部分遍历,因而会导致写的效率一般