HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
1.重要属性
threshold:是 HashMap 所能容纳的最⼤的键值对的个数,threshold = capacity *loadFactor,也就是说 capacity 数组⼀定的情况下,负载因⼦越⼤,所能容纳的键值对个数越多,超出 threshold 这个数⽬就重新 resize(扩容),扩容后的 HashMap的容量是之前的2倍。size 是 HashMap 中实际存在的键值对的数量,注意和 Node[]table 的长度 capacity 、容纳最⼤键值对数量 threshold 的区别
loadFactor:负载因子
2.构造方法
2.1
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
//任何一个int 数字,都能找到离他最近的 2 的幂次方数字(且比他大
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;
}
2.2
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2.3
太烦了可以先不用看
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
3.常用方法
3.1put(K key, V value)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, I;
//步骤1初始化进来
if ((tab = table) == null || (n = tab.length) == 0)
//初始化
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null)
else {
步骤1
Node<K,V> e; K k;
当前hash的key值和hash值一摸一样
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);
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();
afterNodeInsertion(evict);
return null;
}
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;
}
//步骤4 newCap==oldCap*2 ,newThr = oldThr*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 =16和newThr = 0.75*16
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;
//步骤3重新分散分布
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果node后面没有链表或者数组,直接存在新数组的指定位置
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//在新的Node数组中,将该红黑树进行拆分,(如果拆分后的子树过小(子树的节点小于等于6个),则取消树化,即将其转为链表结构);
((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;
//如果e.hash&oldCap进行与运算,算出的结果是为0,即说明该Node节点所对应的数组下标不需要改变
if ((e.hash & oldCap) == 0) {
if (loTail == null)
//如果loTail为null,说明该链表没有头节点
loHead = e;
else
//尾插
loTail.next = e;
loTail = e;
}
else {
//如果e.hash&oldCap进行与运算,算出的结果不为0,则更新该Node节点所对应的数组下标
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
//该Node节点所对应的数组下标不需要改变,直接把数组下标对应的节点指向新Node数组下标位置链表的头节点
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//该Node节点所对应的数组下标需要改变,重新计算出所对应的数组下标值,然后指向新Node数组下标位置链表的头节点
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
1.初始化进来tab和p都是空,执行n = (tab = resize()).length,
然后执行 newCap = 16 ,newThr = 16*0.75=12来着,
然后执行Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
初始化长度为16的table,然后执行tab[i] = newNode(hash, key, value, null);
image.png
2.当再有数据进来的时候,如果没有位置没有占用走tab[i] = newNode(hash, key, value, null);如果占用走putval下面一个else就是步骤1,如果是首节点走首节点,树走树,链表走链表
如果链表长度>=7走treeifyBin(tab, hash)
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();
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);
如果tab的长度<64,走resize()走到步骤3重新分散分布,不然就转化成二叉树
最后执行if (++size > threshold) resize();当putval次数大于阀值,走resize()
就会执行resize的()步骤4扩容,然后数据发散分布
3.2get(Object 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;
}
先查询头节点是不是,不是的话再往下查分节点的东西
扰动函数
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
减少hash冲突
最后hash&(n-1)
网友评论