1.常用属性介绍
HashMap类属性
// 默认容量为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量为2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认加载因子0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转红黑树的链表长度阈值
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转链表的链表长度阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 树化的哈希桶数组容量阈值
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap实例属性
// 哈希桶数组
transient Node<K,V>[] table;
// HashMap有效元素长度
transient int size;
// 阈值
int threshold;
// 加载因子
final float loadFactor;
// HashMap结构被修改次数
transient int modCount;
2.构造函数
2.1 无参构造
public HashMap() {
// 默认设置加载因子为0.75
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
2.2 有参构造
传入容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
需要传入容量和加载因子
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);
}
3.put()
public V put(K key, V value) {
// 具体put方法实现, 详见3.1 putVal()
return putVal(hash(key), key, value, false, true);
}
3.1 putVal()
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) // 判断当前table是否初始化
// 初始化table, 详见3.2 resize()
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) // 计算index,判断对应哈希桶是否为空
// 新增节点存放到该哈希桶上
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))))
// put的hash、key与哈希桶的首节点相等, 将节点赋值给e
e = p;
else if (p instanceof TreeNode) // 首节点是树节点,则调用红黑树的put方法
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else { // put的hash、key与首节点不相等,且不为树节点
for (int binCount = 0; ; ++binCount) {
// 首节点的next节点为空
if ((e = p.next) == null) {
// 使用尾插法,新增节点插入到尾部
p.next = newNode(hash, key, value, null);
// 判断当前链表长度是否大于等于树化阈值
if (binCount >= TREEIFY_THRESHOLD - 1)
// 详见 3.3 treeifyBin()
treeifyBin(tab, hash);
break;
}
// hash、key相等直接跳出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // 找到hash、key相等的节点,直接将value覆盖,并返回原value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 判断当前容量加一是否大于阈值
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
3.2 resize()
初始化或扩容操作
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) { //对table进行扩容
// 如果原容量已经大于等于最大容量2^30次方
// 则设置阈值为int最大值,不再扩容,直接返回原容量
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 将原容量扩容两倍,新容量小于最大容量且原阈值大于默认阈值16时,将阈值也扩容两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
else if (oldThr > 0) // 在调用2.2有参构造函数进行初始化时,将传入的容量处理后赋值给了阈值
newCap = oldThr;
else { // 在调用2.1无参构造初始化时,将容量设置为默认大小16,阈值为12
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) { // 调用2.2有参函数初始化时,对新阈值进行赋值
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;
// 哈希桶不为空时,赋值给e
if ((e = oldTab[j]) != null) {
// 将该哈希桶置位空,方便垃圾回收
oldTab[j] = null;
// 如果当前哈希桶只有一个元素,则根据该节点的hash值与上新容量减一
// 计算出对应在新哈希桶数组的index索引值, 然后将该节点赋值到新哈希桶数组对应位置上
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 { // 该哈希桶的节点数量大于一,且类型不为红黑树节点
// 存储在新哈希桶数组中index与原index相等的链表
Node<K,V> loHead = null, loTail = null;
// 存储在新哈希桶数组中index等于原index加上原容量的链表
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
// 循环遍历该哈希桶
do {
next = e.next;
// 判断当前节点在新哈希桶数组中的index值是否需要修改
if ((e.hash & oldCap) == 0) { // 该节点hash值与上当前hash桶容量为0,表示存储在新哈希桶数组的index值与当前index相同
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else { // 该节点hash值与上当前hash桶容量为1,表示存储在新哈希桶数组的index值等于当前index加上当前哈希桶容量
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;
}
3.3 treeifyBin()
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);
}
}
3.4 hash()
static final int hash(Object key) {
int h;
// key为null时默认存储下标为0,反之则时key的hashcode的高16位与低16位进行异或操作
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
4.get()
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
4.1 getNode()
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) { // 当前哈希桶数组不为空,且对应哈希桶不为null
if (first.hash == hash && // 判断hash、key与首节点的hash、key是否相等
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) { // 判断首节点的next节点是否为空
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;
}