模拟hash桶的put操作:
HashMap的put(key)流程图
demo1
public static void main(String[] args) {
Map<Integer,Integer> map = new HashMap<>(); // 初始化
for (int i=0; i<=1000; i++) {
map.put(i,i); // 添加元素
}
System.out.println(map.get(11)); // 获取元素
}
demo2
public static void main(String[] args) {
HashMap<Integer,Integer> map = new HashMap<>(); // 初始化
for(int i=0;i<=70;i++){
map.put(5+16*i,5+16*i); // 模拟hash碰撞
}
System.out.println(map);
}
new():
//负载因子赋为0.75
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
put():
//put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//hash
//若key==null,hash=0
//key.hashCode()和该hash值右移16位进行异或运算,返回为最终的hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//初始化长度为16
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//若hash位置为null,则不存在hash冲突
//(若n=16,则n-1=15=1111,key在索引范围里&(n-1)结果还等于key,key不在索引范围里&(n-1)相当于对n取余)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//hash冲突
else {
Node<K,V> e; K k;
//key相同,替换
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);
//若key不相同且不为树,则以链表形式追加到尾部
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1)
//尝试调整为红黑树(若node数组长度小于64依然走扩容)
treeifyBin(tab, hash);
break;
}
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;
//size+1>阈值时,调整node数组长度
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//调整node数组长度
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//扩容为2倍,扩容阈值也变为2倍
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) // initial capacity was placed in threshold
newCap = oldThr;
//初始化容量为16,阈值为16*0.75=12,返回长度为16的node数组
else {
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;
//node数组复制,长度改变为新容量
if (oldTab != null) {
//遍历node数组各node
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//若node为null直接跳过,不为空才处理
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//若node没有next,只需要把node上唯一元素按照新hash算法copy到新node数组里
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//若node为树节点,则按照树节点处理方式copy过去
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//否则该节点为链表,则按照链表节点处理方式copy过去
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;
}
//尝试调整为红黑树(若node数组长度小于64依然走扩容)
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//若node数组为null或者node数组长度小于64,走扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//只有当node数组长度大于等于64,才转为红黑树
else if ((e = tab[index = (n - 1) & hash]) != null) {
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);
}
}
get():
//get
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//先根据key的hash定位,再根据key定位
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 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
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;
}