1,我们先用一张思维导图来了解一下HashMap中的put()过程
2,HashMap数据结构
HashMap内部数据结构采用数组+链表+红黑树进行存储。数组类型为Noded[ ],每个Node对象都保存了某个KV键值对元素的key,value,hash,next的值。
public class HashMap{
// 每个Node既保存一个KV键值对,同时也是链表中的一个节点
Node<K,V>[] table;
}
链表节点类:
public class HashMap{
// ...
// 静态内部类Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // 哈希值
final K key; // 键
V value; // 值
Node<K,V> next; // 下一个节点(由于只拥有next,所以该链表为单向链表)
}
// ...
}
3,hashMap的初始容量
默认数组大小为16,下面是源码部分:
public class HashMap{
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 添加键值对
final V putVal(int hash, K key, V value) {
Node<K,V>[] tab; // 数组
Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// 如果数组为空,则该数组扩容为16
n = (tab = resize()).length;
}
}
4,hashMap扩容
由于底层采用数组+链表+红黑树,扩容过程中需要按照数组容量和加载因子来进行判断。
数组容量:基础数组Node<k,v> [ ] table 的长度,如果没有指定容量,添加第一个元素时,默认容量为16。
加载因子:用来表示HashMap集合中的元素的填满程度,默认为0.75.越大则表示允许填满的元素就越多,集合的空间利用率就越高,但是冲突的机会就会增加。反之,如果太小,空间的利用率就低。
下面是HashMap的源代码解析:
public class HashMap{
// 默认链表长度
static final int TREEIFY_THRESHOLD = 8;
// 添加键值对的方法
final V putVal(int hash, K key, V value){
//...
// 将key和value,插入链表尾部
// 循环时,使用binCount进行计数
for (int binCount = 0; ; ++binCount) {
// 判断节点p的next是否空
if ((e = p.next) == null) {
// 插入链表尾部
p.next = newNode(hash, key, value, null);
// 判断链表数量是否大于8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 链表长度超过8,将当前链表转换为红黑树
treeifyBin(tab, hash);
break;
}
}
}
// 转换为红黑树
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 数组长度如果小于64,则优先扩容数组
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);
}
}
}