HashMap的数据结构图
HashMap put流程源码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
table未初始化或者长度为0,进行扩容
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 {
//桶有元素,先比较hashcode,再比较equals
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) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// // 判断链表中结点的key值与插入的元素的key值是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 表示在桶中找到key值、hash值与插入元素相等的结点
if (e != null) {
// 记录e的value
V oldValue = e.value;
// onlyIfAbsent为false或者旧值为null
if (!onlyIfAbsent || oldValue == null)
//用新值替换旧值
e.value = value;
// 访问后回调
afterNodeAccess(e);
// 返回旧值
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
- 如果table大小为0或者未初始化,进行扩容
- 桶为空,新生成结点放入桶中
- 桶不为空,先比较hashcode,再比较equals
- 红黑树处理方法
- 找到相同值或者为空,则新值替换旧值
HashMap get流程源码
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods.
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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;
}
- 首先根据 hash 方法获取到 key 的 hash 值
- 然后通过 hash & (length - 1) 的方式获取到 key 所对应的Node数组下标 ( length对应数组长度 )
- 首先判断此结点是否为空,是否就是要找的值,是则返回,否则进入第二个结点。
- 接着判断第二个结点是否为空,是则返回,不是则判断此时数据结构是链表还是红黑树
- 链表结构进行顺序遍历查找操作,每次用 == 符号 和 equals( ) 方法来判断 key 是否相同,满足条件则直接返回该结点。链表遍历完都没有找到则返回空。
- 红黑树结构执行相应的 getTreeNode( ) 查找操作。
HashMap 扩容源码
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 { // 未声明容量时,第一次调用resize,直接用默认容量(16)和扩容因子(0.75)
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 { // 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;
}
- 当第一次向map里面添加数据,或添加完数据后的大小,大于阈值的大小,这时候就会进行扩容
- 如果有初始容量,比如new hashmap(24),此时 初始容量为32(hashmap必须保证容量为2的n次方),阈值= 扩容因子*初始容量=24;达到24个时,扩容为64个,阈值=64*0.75=48
- 如果没有初始值,默认初始容量为16,阈值为12;达到12个时,扩容为32,阈值为32*0.75 = 24; (源码中扩容后阈值=当前阈值*2)一个意思
- 将旧的数据复制到新的hashmap中
Hashmap容量为什么必须是2的n次方?
因为hashMap为了存取高效,要尽量较少碰撞,就是要尽量把数据分配均匀,使得每个链表长度大致相同。关键就在于把当前数据存放到哪一个桶中(哪个节点node上),
实现这个目标的算法就是取模运算(%)
而位运算(&)效果更好,为了代替取模运算(%)
当容量为2的n次方时,hash & (capacity - 1) == hash % capacity
所有Hashmap容量必须是2的n次方