用了2年的hashmap,一直都是看别人的博文,懂了一点原理,今天点进 jdk1.8 的源码,从头理顺它。
- 从数据结构上来看,hashmap采用数组+链表+红黑树(当hashmap的size >= 64 && 单个链表长度>8 )的方式来达到最快的访问速度
- 从算法上来看,hashmap最主要的就是采用了hash算法
HashMap类的属性
// 默认的初始容量是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的填充因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 结点数大于这个值(并且size > 64时)时会转成红黑树,泊松分布的计算公式,链表中元素个数为8时的概率已经非常小
static final int TREEIFY_THRESHOLD = 8;
// 当桶(bucket)上的结点数小于这个值时树转链表
static final int UNTREEIFY_THRESHOLD = 6;
// 桶中结构转化为红黑树对应的table的最小大小
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;
// 临界值 当实际大小(容量*填充因子)超过临界值时,会进行扩容
int threshold;
// 填充因子
final float loadFactor;
Hash算法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 初始化h
- 调用object类的hashCode方法,算出值
- 将2得到的值转换成二进制 右移16位,将高16位换到低16位,原高16位补0(使用高16位参与运算为了降低hash冲突)
- 将2的值和3的值 做^(异或)运算
- 此方法当key!= null 时,返回4的值
put()方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab 哈希桶 // p 哈希桶上的节点
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果table未初始化为空 或者 table的长度为0,执行resize()方法,初始化hashMap
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//计算i=长度-1 和 hash值 进行与运算,相当于进行取模,拿到tab数组上的位置,判断是否为
空,为空则新建一个Node对象,并放在tab数组上
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//tab数组当前位置存在对象,产生了hash冲突
else {
Node<K,V> e; K k;
//此时,p为tab数组上与当前产生哈希碰撞的 Node对象
//hash值相同,key值相同,直接覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果p是红黑树节点,那么调用红黑树的put方法
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 - 1时,转为红黑树,跳出循环
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//// 判断链表中结点的key值与插入的元素的key值是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//找到key值和hash值都相同的点,直接替换value值,并返回
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//结构性修改,记录被修改的次数
++modCount;
//如果 size值 大于阈值,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize()方法
final Node<K,V>[] resize() {
//初始化获得原数组,oldCap原数组长度,oldTHr原阈值,newCap新长度, newThr新阈值
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//如果原数组长度>=最大容量,阈值为Integer的最大,2的32次幂
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
}
//原数组未初始化,初始化参数
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;
//e为原来的元素
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//此处元素为单个元素,新的位置为hash & 长度-1
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);
// 将分组后的链表映射到新桶中
//这种说明元素的hash 第5位为0 类似00000000
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//这种说明元素的hash 第5位为1 类似00010000
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
创建一个hashmap
Map map = new HashMap<>();