HashMap源码分析(Java8)
一、put()
Map map = new HashMap();
map.put("one", 1);
1.默认值和重要参数
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int TREEIFY_THRESHOLD = 8;
int threshold;
static final int MAXIMUM_CAPACITY = 1 << 30;
2.构造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
3.put()
往map中加入数据
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
4.hash()
对key的hashCode进行转换,将高位的影响向低位进行传播,使散列集的分布更合理。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
java中>>表示带符号位右移,正数高位补0、负数不1;>>>为不带符号位右移,不论正数还是负数高位通通补0。
(h = key.hashCode()) ^ (h >>> 16)
java中hashcode是32位的,假设key的hash值为0011 0101 0111 1001 1111 1101 1010 1001
0011 0101 0111 1001 1111 1101 1010 1001
^ 0000 0000 0000 0000 0011 0101 0111 1001
0011 0101 0111 1001 1100 1000 1101 0000
5.putVal()
第一次添加数据,会先创建一个保存链表(或红黑树)的数组,将前面处理过的hashCode与数组长度-1进行与运算(tab[i = (n - 1) & hash]),得到数据应该保存的位置。(n - 1,因为是从0开始加入元素)
- 该位置处没有链表,就创建新节点(传入的数据存在节点中),将新创建的节点作为链表头节点存入该位置。
- 该位置处有链表,遍历链表,如果链表中的节点key与传入的key相同,就将旧有的value替换成新的value,并返回oldValue;如果遍历完链表都没有找到key相同的节点,就创建新的节点并保存在链表尾(尾插法)。
- 将节点插入链表后,链表的长度大于等于TREEIFY_THRESHOLD = 8时,会将链表转为红黑树。
- 第一次put数据或者当数组长度大于threshold时会调用resize()创建数组或对数组进行扩容。
- 插入数据HashMap的size会加1,修改不会。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
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 {
Node<K,V> e; K k;
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)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
6.resize()
-
第一次put,保存链表的数组不存在,会创建新数组,新数组的大小为16,设置阈值为0.75*16=12 newCap = DEFAULT_INITIAL_CAPACITY;//第一次put,设为默认容量16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//初始容量满了,进行扩容的阈值 -
不是第一次put,也是就是map的大小达到了阈值,就要对map进行扩容,创建大小为原数组大小2倍的新数组,将原数组中的数据存入新数组。阈值也是原阈值的2倍,160.75->160.75=32*0.375也就是扩容一次阈值因子减半。
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;
}
else if (oldThr > 0)
newCap = oldThr;
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;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
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;
}
二、get()
String value = map.get("one");
1.get()
调用getNode()找到与key对应的节点。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
2.getNode()
first = tab[(n - 1) & hash],数组长度与key的hashCode与运算得到链表存储的位置,通过位置直接在数组中获取到链表的头节点。如果头节点key与传入的key相等直接返回,不一样,则轮询链表找到与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 &&
((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;
}
三、remove()
1.remove()
调用removeNode(),删除成功返回value,失败null。
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
2.removeNode()
就是通过key的hashCode确定数组下标,通过下标找到链表,轮询链表,找到相应的节点,再将该节点的前驱节点的next指向该节点后继节点的过程。
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
|