前言
看图说话,这个map的一个大框的结构。实际编程中,我其实最常用到的就是hashmap,其他hashtable,treemap我都没有用到过。此博文用来整理一下关于集合Map的认知。详细的分析一下hashmap的成长过程与底层原理实现,探究源码。
个人总结
hashmap,线程不安全,为什么不安全之后会分析。key允许存储一个为null,value允许多个存储。
hashtable与hashmap对应,线程安全,只有一个线程可以写hashtable,所以并发性不高。用sychronized实现了。
treemap很少用到,他的功能是因为他实现了SortedMap的接口,把他保存的记录按照键的升序排序,
package test;
import java.util.HashMap;
import java.util.TreeMap;
/**
* @Classname Test
* @Description TODO
* @Date 2020/3/9 14:38
* @Created by mmz
*/
public class Test {
static class xixi{
String name;
xixi(String name){
this.name = name;
}
}
public static void main(String[] args) {
TreeMap<xixi,Integer> treeMap = new TreeMap<>();
treeMap.put(new xixi("1"),2);
treeMap.put(new xixi("4"),5);
treeMap.put(new xixi("6"),7);
System.out.println(treeMap);
}
}
如果你想使用treemap,key一定要实现Comparable接口,否则会在运行的时候报出异常。
hashmap的内部实现
先说结论,hashmap在1.7版本的时候只是数组+链表,1.8版本的时候加入了红黑树。红黑树的查询效率比链表要快,所以当hashmap的node节点数大于64并且单个entry上面的节点数>=8,这是链表转成了红黑树。
Node<k,v>
可以看到最核心的东西就是hashmap拥有一个Node<K,V>类型的一个table数组。
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; }
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;
}
}
这个node<k,v>继承了Map.Entry<K,V>,那么就说明了数据结构是一个node类型的数组,node类型有一个键值对,并且拥有一个node类型的next的指针。
其他的字段
在理解hashmap如何进行put的操作或者扩容之前,还有几个比较重要的字段
int threshold; // 所能容纳的key-value对极限
final float loadFactor; // 负载因子
int modCount;
int size;
最开始hashmap如果在使用默认情况下面的构造函数,容量为16,负载因子为0.75,也就是说如果节点超过了16*0.75=12的时候,就会进行扩容操作。扩容之后,容量是原来的二倍(一定是2的倍数,下面会说)
size是实际存在的键值对数量,modCount是内部结构发生变化。
获取索引位置hash函数
不管进行任何的操作,第一步都是定位到这个table中的位置,在进行下一步操作。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
1)获取哈希值,h=key.hashCode()
2)高位运算与低16位进行异或运算
还有一个操作,1.7是自立一个函数
static int indexFor(int h, int length) { //jdk1.7的源码,jdk1.8没有这个方法,但是实现原理一样的
return h & (length-1); //第三步 取模运算
}
1.8是在put函数里面进行取索引
1.7版本
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
hashmap的put方法
1)判断当前的table是否进行初始化了,如果没有先进行初始化
2)计算hash值,找到索引,判断table[index]
3)如果当前index == null ,那么直接插入
4)如果不为null,在判断,key是否存在
5)如果存在,判断这两个节点是否相等,如果相等进行覆盖
6)如果两个节点不相等,那么进入链表或者红黑树的操作。
7)最后判断是否需要扩容
8)完成操作
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) {
//判断table数组是否为空
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果为null,直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//判断一下插入的key与当前数组对应的索引是否为同一个
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果相同覆盖
e = p;
//如果不同判断当前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);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//判断链表是否equals
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;
//如果长度过大,进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容机制
扩容就是当前的size大于当前的阈值了。需要把当前的hashmap进行扩容。
源码分析
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次幂
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;//修改阈值的int的最大值
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
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"})
//也就是以前的transfer函数
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) {//得到旧的数组的元素node
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;
}
jdk1.8相比1.7元素在重新计算hash之后,因为n变为2倍,那么n-1的mask范围在高位多1bit(红色),因此新的index就会发生这样的变化:
这个设计非常的巧妙,省去了重新计算hash值的时间,并且在扩容的过程中,均匀的把之前的节点分散到了新的bucket中。
而且有一点注意区别,JDK1.7中rehash的时候,旧链表迁移新链表的时候,如果在新表的数组索引位置相同,则链表元素会倒置,但是从上图可以看出,JDK1.8不会倒置。
hashmap1.7版本为什么会形成环形链表
1.7版本,因为是头插法,如果两个线程同时在resize之后,transfer代码。此时两个线程已经都添加了数据。
注意,Thread1的 e 指向了key(3),而next指向了key(7),其在线程二rehash后,指向了线程二重组后的链表。
线程一被调度回来执行,先是执行 newTalbe[i] = e, 然后是e = next,导致了e指向了key(7),而下一次循环的next = e.next导致了next指向了key(3)。
e.next = newTable[i] 导致 key(3).next 指向了 key(7)。注意:此时的key(7).next 已经指向了key(3), 环形链表就这样出现了。
jdk1.7与1.8版本的比较优化
数组+链表改成了数组+链表或红黑树;
效率提高,从n降到了logn
不直接使用红黑树的原因,是因为红黑树的插入删除很重,节点数不如链表。
链表的插入方式从头插法改成了尾插法,简单说就是插入时,如果数组位置上已经有元素,1.7将新元素放到数组中,原始节点作为新节点的后继节点,1.8遍历链表,将元素放置到链表的最后;
不会出现环形链表
扩容的时候1.7需要对原数组中的元素进行重新hash定位在新数组的位置,1.8采用更简单的判断逻辑,位置不变或索引+旧容量大小;
在插入时,1.7先判断是否需要扩容,再插入,1.8先进行插入,插入完成再判断是否需要扩容;
jdk1.8版本也是线程不安全的
如果有线程A与B,同时对一个值进行赋值。当A执行完,第六行的代码,由于cpu的时间片,导致挂起。线程B得到时间片开始进行操作,操作完毕。A获得时间片,由于之前已经进行了hash碰撞的判断,所有此时不会再进行判断,而是直接进行插入,这就导致了线程B插入的数据被线程A覆盖了,从而线程不安全。
ConcurrentHashMap怎么实现的
ConcurrentHashMap成员变量使用volatile 修饰,免除了指令重排序,同时保证内存可见性,另外使用CAS操作和synchronized结合实现赋值操作,多线程操作只会锁住当前操作索引的节点。
个人感想
在扩容的时候也用的hash &(length-1)
这样的话,原来的元素如果新加的一位为1,那么就增大扩容的容量。若还是为0,就不会动。
把容易有哈希冲突的这种的方式分为了两份。
判断的时候1.8用的扰动函数
h ^ h>>>16
哈希值与当前低16位的值异或,这样得出来的hash比较均匀,不容易出现冲突。
在数据结构中,我们处理hash冲突常使用的方法有:开发定址法、再哈希法、链地址法、建立公共溢出区。而hashMap中处理hash冲突的方法就是链地址法。