环境
本次源码根据JDK1.8分析
HashMap声明
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
HashMap<K,V>继承了AbstractMap<K,V>,并且实现了Map<K,V>, Cloneable, Serializable接口,表明HashMap可以复制,也可以序列化。
初始容量
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
HashMap的默认初始化容量是16。
最大容量
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
HashMap的最大容量是2的30 次方。
默认加载因子
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
默认加载因子是0.75,为什么是0.75?
如果加载因子过小,那么会频繁进行扩容操作,扩容也会带来性能上的消耗,而加载因子过大,会大大增加hash冲突的概率,从而影响性能。
还有几个常量,此处我们先记住它们,后面会用到。
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
结点声明
static class Node<K,V> implements Map.Entry<K,V>
是一个node结点。
那么来看看它有哪些东西
final int hash;
final K key;
V value;
Node<K,V> next;
public final K getKey() { return key; }
public final V getValue() { return value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
//省略
}
public final boolean equals(Object o) {
//方法体暂时不看
}
put方法
先看看源码吧
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
显然从这里看不到具体细节,直接上putVal(hash(key), key, value, false, true)源码
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)
//resize()为实际的扩容方法
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))))
//哈希相等并且通过equals比较值也相等,将待存的元素放到e中
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//如果此位置上是链表结构,还要和每一个元素进行比较,直接循环
for (int binCount = 0; ; ++binCount) {
//如果发现该位置就只有一个p元素
if ((e = p.next) == null) {
//直接尾插法插入该节点
p.next = newNode(hash, key, value, null);
//将链表转换成红黑树的情况,链表长度大于等于8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//p.next存在,就进行hash值和equals的比较。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//相等就退出去,进行替换
break;
//循环控制
p = e;
}
}
//如果e!= null 说明已经有一个key了,将它的旧值进行返回并用新值覆盖原来的旧值
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;
}
resize方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//第一次扩容,oldtable为null,赋值为0
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; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//初始化新数组的长度为16
newCap = DEFAULT_INITIAL_CAPACITY;
//16*0.75 需要扩容的阈值12出现
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"})
//newCap为16,初始化新数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//将造好的数组给table
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;
}
转化成红黑树的方法
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)
//当前数组的长度小于64,那就去扩容,不要构成树结构
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);
}
}
通过以上源码的大致分析,可以总结一下几点:
- HashMap在jdk1.8中采用的是数组加链表加红黑树的方式,而在jdk1.7中采用的是数组加链表的方式。
- 初始化时并没有直接创建数组,而是在第一次put的时候去创建数组。
- 链表转化红黑树的时机:链表长度大于等于8,并且数组的长度大于64。
- 初始容量为16,默认加载因子0.75,每次扩容为原来的2倍。
- 可以有一个null键,可以有多可null值。
- 线程不安全。