昨天面试时,面试官问hashMap如果初始容量设置为13会怎么样?因为知道hashMap的容量为2的幂次,所以猜测应该是取离设置的值最近的二的n次幂,离13最近的应该是16,虽然蒙对了,但心里很虚,所以继续来看hashMap的源码
- HashMap的类关系图,把面试中经常被问的相关的类也列出来了,hashTable, concurrentHashMap等,从这张结构图可以看到它们之间的其中一个区别就是:hashMap和concurrentHashMap 都继承自AbstractMap,而hashTable继承自Dictionary.
HashMap声明了以下几个成员变量
/**
*默认的初始化容量,如果构造函数里不传这个值,就取默认的16,容量必须是2的n次方
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量 2的30次方
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认的负载因子,如果元素数量 > 设定容量 * 负载因子时会启动扩容机制
* 比如容量为16,当容器中元素个数大于16*0.75=12时,会进行扩容
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 当链表中的元素个数 >= TREEIFY_THRESHOLD - 1(7) 并且数组长度 >= MIN_TREEIFY_CAPACITY (64),链表会转换成红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 当链表中的元素个数 <= UNTREEIFY_THRESHOLD(6) 时,红黑树会转换成链表
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 链表转换成红黑树的最小数组大小
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 这个就是hashMap的数组了,存放的是Node节点(treeNode是Node的孙子类)
*/
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* map中的数据元素个数
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
/**
*扩容阈值,元素个数达到这个值时,需要扩容 ,当前容量*负载因子,初始默认情况下(16*0.75 = 12)
* The next size value at which to resize (capacity * load factor).
*
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* 负载因子
*/
final float loadFactor;
新建HashMap 对象
Map<String,Integer> map = new HashMap<>(13); //如果不带参数,默认16,主要看一下如果设置初始容量不为2的n次方,会如何处理?源码如下:
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);
}
从源码可以看到分三种情况:
1.初始容量如果小于0,直接抛异常
2.初始容量如果大于规定的最大的值(2^30),设置为最大值
3.否则会取最近的大于等于该值的2的n次方,具体方法在tableSizeFor()中,
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1; // 以13为例, n=13-1 = 12 二进制表示 1100
n |= n >>> 1; // 1100 左移一位 0110 | n = 1110 => 14
n |= n >>> 2; // 1110 左移一位 0111 | 1110 = 1111 => 15
n |= n >>> 4; // 1111左移一位 0111 | 1111 = 1111 => 15
n |= n >>> 8; // 1111左移一位 0111 | 1111 = 1111 => 15
n |= n >>> 16; // 1111左移一位 0110 | 1111= 1111 => 15
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; //n+1 = 16
}
接下来看看put()方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
对key进行重hash,获取新的hash值,这里使用右移与异或运算的原因查了很多文档,答案有很多,大概意思都是说为了减少hash冲突,但是讲的都不是很透彻,(先留一个坑,后面补吧//TODO),看这篇有感觉,但是还不是很明确:
https://www.cnblogs.com/zxporz/p/11204233.html
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
以下是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) //第一个if初始化table
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //第二个if 数组的i位置没有元素,直接插入
tab[i] = newNode(hash, key, value, null);
else { //如果数组下标为i的位置,有数据的话 有三种情况
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) //情况1:如果要插入的元素和已存在的元素hash值相同 并且key也相同,当作更新直接覆盖
e = p;
else if (p instanceof TreeNode) //情况2:如果i位置的元素是红黑树节点,则按照红黑树的规则插入,不需要考虑链表和红黑树的转换
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else { //情况3:i位置的元素是普通链表节点。无条件遍历链表,如果链表长度小于7,直接插入到链表末尾,否则执行转换的方法 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
//这个方法是链表转红黑树的方法,方法内部会判断数组长度是否大于64,如果大于,才会转换,否则进行扩容resize()
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
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;
}
1.初始化table数组阶段(第一个if模块)
如果数组为空或者数组长度等于0,调用resize()方法初始化数组,获得数组的长度,这里为了逻辑清晰只截取了初始化部分的代码,扩容相关的后面再说
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//第一次put的时候oldCap,oldThr , threshold 都是 0,所以走else{}的逻辑,其他的逻辑代码都被我省略了。。。
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {。。。}
else if (oldThr > 0) {。。。}
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; //16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //0.75 * 16 = 12
}
。。。
threshold = newThr; //12
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab; //初始化一个长度为16的数组
//这里关于数据迁移的代码省略了。。。。
return newTab;
2.添加节点:第二个if之后的逻辑
- 根据hash值计算数组下标i : i = (n - 1) & hash 当n=2的n次方时等价于 hash % n
- 判断当前位置有没有数据,如果没有直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); - 如果当前位置有数据
3.1 则判断当前位置数据的hash值是否和要插入的数据的hash值相同,如果相同,继续比较key是否相同,如果相同则覆盖,并临时存储旧数据。
3.2 不相同则表示当前数组位置的数据个数大于等于1,可能是链表,也可能是红黑树,所以先判断是不是树节点。不管是什么节点都要遍历查找所有节点,看是否和待插入数据相同,相同则覆盖并且保存旧数据,否则插入到合适的位置,链表插到末尾,如果链表长度大于7,并且数组长度大于64,要转换成红黑树,红黑树要做平衡转换。 如果是更新返回旧数据的value,否则返回null.插入操作完成之后要判断如果目前size 大于阈值,要进行扩容
3.扩容
以第一次扩容为例,当size > 12时第一次扩容,这里写了一个小demo用来跟踪扩容
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
for(int i=0; i<20; i++){
map.put("a"+i,i);
}
}
hashMap的链表中的数据有高位和低位之分,e.hash & oldCap == 0 是低位,否则是高位,低位的数在扩容后位置不变,高位的数在扩容后位置=原来的位置加上原来的容量,代码中的体现就是j + oldCap,我觉得这也是hashMap的容量要设置为2的n次方的一个原因之一,但是网上没找到相关的解释,只是我的一个猜测而已。
如果原来的数组位置只有一个节点,则直接用公式计算新的位置插入, newTab[e.hash & (newCap - 1)] = e;
如果节点数大于1,则循环遍历判断每个节点是高位还是低位,放入对应的新的位置
以下是源码
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table; //存放了13个数据
int oldCap = (oldTab == null) ? 0 : oldTab.length; //16
int oldThr = threshold; //12
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//lodcap == 16 走这部分逻辑 给newCap赋值 = 16*2=32 newThr = 12 * 2 = 24
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
//这里是初始化的逻辑,前面有看过
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);
}
//更新阈值为24
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;
}
get(key)方法:
首先计算对key进行重hash,使用(n-1) & hash 获取下标位置。对比第一个元素的hashCode和key值,判断是否是要查找的元素,如果不是,再遍历链表或红黑树获取要查找的元素
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
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;
}
clear()
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
就写到这里吧。。。。留下的坑,慢慢填,好多不会的地方啊