1. 内部由内部类Node存储单节点数据,Node单向链表(hash冲突时往后放)。table为Node数组,hash后决定Node存在table[?]
static class Node<K,V> implements <K,V> {
Node<K,V> next; //单链表
2. Node的构造函数
Node(int hash, K key, V value, Node<K,V> next)
3. 新建无参HashMap的初始化容量为16(在第一次put()时会调用到resize()来初始化容量)
4. HashMap的容量【必须】为2的次方数
/*** The default initial capacity - MUST be a power of two.[源码注释]*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
容量为2次方的原因,Why does HashMap require that the initial capacity be a power of two? - Stack Overflow
源码计算key的index值,tab[i = (n - 1) & hash]
static int indexFor(int h, int length) { // h for hashcode of key, length of hashmap
return h & (length-1);
}
当hashmap的容量为2次方时,通过key的hashcode来计算在map内部的table的index时更方便,效果更好
5. put()
- hash()得出key的hash值
int h;//hash值
return (key == null) ? 0 : (h = ()) ^ (h >>> 16);
- 对应的table[?]没有占用,即未冲突,new Node放入table数组
if ((p = tab[i = (n - 1) & hash]) == null) //(n - 1) & hash为计算出的位置,n为容量,hash为上面计算的key的hash值
tab[i] = newNode(hash, key, value, null);//无冲突直接放入第一个node,注意第四个参数null
-
对应的table[?]被占用,判断当前的node是否相同,相同为铺盖操作(更新value),不同为碰撞(用遍历后加入)
-
如果碰撞到8次(同一table[?]后面链接了有8个),会把链接改为【红黑树结构】存储
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash); //转红黑树结构