HashMap
数据结构
int size; 数据量
Node<K,V>[] table; hash表
int threshold; 扩容临界点 threshold=table.length*loadFactor
float loadFactor; 填装因子
TreeNode、Node属性至关重要.
构造方法
public HashMap();
初始化factor
public HashMap(int initialCapacity)与
public HashMap(int initialCapacity, float loadFactor)
初始化factor、threshoud=tablesizefor(initialCapacity);
查找大于等于cap,且最近的2的整数次幂的树,eg.10->16,5->8
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;
}
resize方法
源码流程图:
单链表copy Node节点(单链表)
遍历单链表分解成两个单链表,分别放置low位置,与high位置
红黑树copy TreeNode节点(利用了其双链表的性质)
遍历单链表的分解成两个单链表A、B, 如果长度<=6解树
解树:调用untreeify把树节点变成Node节点;
如果长度>6,调用treeify遍历链表重新构造红黑树;
treeifyBin:把Node节点变成红黑树节点,并调用treeify
treeify:把TreeNode节点构造成红黑树
源码分析
/hashMap扩容操作
// oldTab未扩容的桶,oldCap未扩容的桶大小,oldThr未扩容时的阈值;
// newTab扩容后的桶,newCap扩容后的桶大小,newThr扩容后的阈值;
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) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0)
// 有参数的构造方法第一次put会进到这里;
//初始化table为空,initSize经过tableSizeFor运算返回一个数,这个数是2^n并且大于等于initSize;取最小2^n值;把这个数作为table第一次初始化的大小
newCap = oldThr;//把计算好的阈值设置为下次要扩容的大小
else { // 无参构造方法第一次进入这里
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
//有参数的构造方法第一次put会进到这里;
//在这里重新计算扩容后的阈值
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];//新建一个nodeTable
table = newTab;//把原来的table指向新table
if (oldTab != null) {
//如果是扩容操作就把原来的数据放到新的table中
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//原来位置上只有一个node的直接挪过去
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//原来位置是红黑树的拆分红黑树
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { //原来是链表的拆分链表
//拆分之后的位置,要么在原来的位置不变,要么在原来的位置上的基础上+扩容的大小的位置上;
// loHead:原来位置上的链表头, loTail:原来位置上链表尾
Node<K,V> loHead = null, loTail = null;//原来的位置
// loHead:新位置上的链表头, loTail:新位置上链表尾
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;
}
put、balanceInsertion方法
源码流程图:
//hashMap插入操作
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
// onlyIfAbsent=true,则不允许覆盖; evict=false,在构造模式下(HashMap第四个构造函数)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// tab:桶;p:当前节点; n:桶的大小; i:p在桶的位置
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//桶为空或者长度为0扩容
if ((p = tab[i = (n - 1) & hash]) == null)
//如果在桶中的位置为空,把桶的值设置为Node
tab[i] = new Node(hash, key, value, null);
else {//1.桶中已经有node ; 2.链表 3.红黑树
Node<K,V> e; K k;
//e最终指向oldValue(最后用Value覆盖oldValue)
//k:e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//1.桶中的node的key和传入的key相同,进行覆盖操作
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//3.红黑树插入操作
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;
}
//链表上存在就进行覆盖
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
//2.链表插入操作
}
//e指向oldValue,把Value对oldValue覆盖
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//覆盖就返回oldValue
return oldValue;
}
}
//非覆盖返回null,容器修改的次数+1
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//计算key值在桶中的位置
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
putTreeVal
//在红黑树中找到合适的位置并插入
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)//左子树
dir = -1;
else if (ph < h)//右子树
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;//key相同返回节点
//key的hash相同,但是却是不同的东西,使用另外的手段确定位置
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
//找到了插入位置
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
//插入之后,把树的root节点按照它的链式结构移动到链头
//这里的TreeNode,不仅是一种树结构,还保存了双链表结构,把树的root节点和链表头节点设置成同一个节点,其树结构用于快速查找,链表结构遍历整棵树或者使用链表遍历拆分整棵树,
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
tieBreakOrder:当key的hash值相同,且key都没有实现comparable时,定义一个新的比较方法
treeifyBin
作用:Node节点转换成TreeNode节点,并调用treeify
//Node节点转换成TreeNode节点
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();//当桶的容量<64时,优先考虑扩容
else if ((e = tab[index = (n - 1) & hash]) != null) {
//依次把桶上指定位置的链表节点转换为树节点
//hd指向头节点,t1执行e的前一个节点
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);
}
}
treeify
作用:遍历TreeNode节点,构造红黑树
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
//遍历插入
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
//空树
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
//非空,找到位置插入
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
//找插入的位置
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)//左
dir = -1;
else if (ph < h)//右
dir = 1;
//hash相同,但类却不同,使用其他方法比较
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
//插入
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//插入后平衡树
root = balanceInsertion(root, x);
break;
}
}
}
}
//root节点移动到链头
moveRootToFront(tab, root);
}