|-- Node<K,V>[] table; // 存数据的结构
int threshold;
|-- new HashMap<>() {
// DEFAULT_LOAD_FACTOR = 0.75f
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
|-- put(key, value) {
Node<K,V>[] tab;
int n;
int i; // i = (tab.length - 1) & hash
boolean isTableEmpty = (tab = table) == null || (n = tab.length) == 0;
if (isTableEmpty)
n = (tab = resize()).length;
boolean isValueEmpty = ((p = tab[i = (n - 1) & hash]) == null);
if (isValueEmpty)
tab[i] = newNode(hash, key, value, null);
else {
// TODO
Node<K,V> e;
boolean isEqHashAndKey = p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k));
if (isEqHashAndKey)
e = 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;
}
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();
}
|-- 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) { // >= 2的30次方
threshold = Integer.MAX_VALUE; // = (2的31次方-1)
return oldTab;
} else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY){ // (oldCap x 2) < 2的30次方 && oldCap >= 16
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; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 0.75*16
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE); //
}
threshold = newThr;
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// TODO
}
return newTab;
}
|-- get(key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
boolean isExsitsFirst = ((tab = table) != nul && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null);
if (isExsitsFirst) {
if (first.hash == hash &&
((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);
}
}
}