一、HashMap之 初次见面
初次见面先送给大家两张张图
上图中,白色部分是接口,黄色部分是要重点了解的,最好是看一遍源码,绿色部分已经过时,不常用了,但是面试中可能会问到。
1.1HashMap入门
个人代码:
public static void main(String[] args) {
Map<String, String> map = new HashMap();
map.put("k1","v1");
map.put("k2","v2");
map.put("k3","v3");
map.put("k4","v4");
map.put("k5","v5");
System.out.println(map.size());
}
老规矩先看它的构造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* The load factor used when none specified in constructor.
* 翻译:构造函数中没有指定时使用的负载因子。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The load factor for the hash table.
* 翻译:哈希表的加载因子。
*
* @serial
*/
final float loadFactor;
是不是有点似曾相识啊?我们ArrayList的构造方法是不是也是这样,创建一个空数组?代码一样吧?不过这里是赋了个成员变量加载因子个常量值 0.75f
我们再看看还有没有成员变量
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
* 翻译:表,第一次使用时初始化,并将大小调整为
* 必要的。当分配时,长度总是2的幂。
* (在某些操作中,我们还允许长度为零
* 当前不需要的引导机制。)
*/
transient Node<K,V>[] table;
这是什么?Node对象,我们之前在讲LinkedList时也就是这玩意。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
点进去之后我们看到这也是一个静态的内部类,但LinkedList那是一个私有的静态内部类。
注意:私有只能内部使用。如果在变量前不加任何访问权修饰符,它就具有默认的访问控制特性,也称为friendly变量。它和保护变量非常像,它只允许在同一个包中的其他类访问, 即便是子类,如果和父类不在同一包中,也不能继承默认变量(这是默认访问变量和保护变量的唯一区别)。因为它限定了访问权限只能在包中,所以也有人称默认 访问权限为包访问权限。
key、value 大家都知道就是用来存 put 的key、value
next 看过LinkedList 文章的就知道是 标记节点的下一个元素了。
/* ---------------- Fields -------------- */
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
* 翻译:表,第一次使用时初始化,并将大小调整为
* 必要的。当分配时,长度总是2的幂。
* (在某些操作中,我们还允许长度为零
* 当前不需要的引导机制。)
*/
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
* 翻译:保存缓存entrySet ()。注意,使用了AbstractMap字段
* 用于keySet()和values()。
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this 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;
/**
* The next size value at which to resize (capacity * load factor).
* 翻译:要调整大小的下一个大小值(容量*负载因子)。
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
// 翻译:(序列化时javadoc描述为true。
// 此外,如果没有分配表数组,则执行以下操作
// 字段保存初始数组容量,或零表示
// DEFAULT_INITIAL_CAPACITY)。
int threshold;
/**
* The load factor for the hash table.
* 翻译:哈希表的加载因子。
*
* @serial
*/
final float loadFactor;
size是逻辑长度,modCount是记录修改次数,threshold。 这个threshold = capacity * load factor 。当HashMap的size等于threshold时,就要进行resize,也就是扩容。
我们再来看看 put 方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
很简单 调了一个 putVal()再看这个方法之前有个 hash() 也带大家看一下
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
主要就是用来计算key 的 hash值,这里有个面试题:hashmap的key可以为空吗?当然可以,因为 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
/**
* 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.翻译:如果为false,则该表处于创建模式。
* @return previous value, or null if none 翻译:前一个值,如果没有,则为空
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {// hash:3366 key:k1 value:v1 onlyIfAbsent:false evict: true
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//n:16
if ((p = tab[i = (n - 1) & hash]) == null)//p:null i:6 n:16
tab[i] = newNode(hash, key, value, null);//tab[6] newNode(3366,"k1","v1",null)
else {
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;
}
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;//modCount:1
if (++size > threshold)
resize();
afterNodeInsertion(evict);//不做任何操作
return null;
}
resize() 看看
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;//oldTab :null
int oldCap = (oldTab == null) ? 0 : oldTab.length;//oldCap :0 oldTab:null
int oldThr = threshold;//oldThr :0
int newCap, newThr = 0;//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 { // 进入else
newCap = DEFAULT_INITIAL_CAPACITY;//newCap :16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//newThr:12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;//threshold:12
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//Node数组长度是16
table = newTab;//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;//返回
}
//计算新的resize上限
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
看一下上面这段代码,你有没有考虑过hashmap扩容机制为什么是0.75?
我们先假设如果我们设置为 1,会怎么样?
首先我们以初始值为16的数组长度为例子,如果loadFactor = 1
,也就是说只有当数组的每一个下标都存有元素的时候才会扩容,我们知道当数组下标发生碰撞时会产生链表
,当链表长度达到8时会转化成红黑树
,考虑下最坏的情况,每次我们put的时候都发生了碰撞,那么每个数组元素都带有一个红黑树,这样查询效率会非常低下,但是,空间利用率会很高
。
我们再假设一下,如果我们设置为 0.5 会怎么样?
首先我们以初始值为16的数组长度为例子,如果loadFactor = 0.5
,也就是说只要数组里有8个元素就会扩容
,考虑下最坏的情况,每次我们put都没有重复的下标索引,那么每存一半的元素就要进行一次扩容
,这样查询效率会很高,但是,空间利用率非常低
。
我们这些做开发的永远是在时间复杂度和空间复杂度上做平衡,所以我们选个折中的数。
这里面有一个扩容机制,扩容的长度总是2的幂次方。2 - 4 - 8 - 16 - 32 - 64
有没有想过一个问题啊,为什么扩容非要是2的幂???
这里大家看一下这串代码if ((p = tab[i = (n - 1) & hash]) == null)
首先(n - 1) & hash
这段代码做了两件事,第一:保证了put()方法存放的元素位置,一定在数组下标范围内。
第二:(n - 1) & hash
就等同于 hash % n
(前提是n为2的幂) 之所以采用前者,是因为 &
运算效率比%
要快。
DEFAULT_INITIAL_CAPACITY
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
其实上面说了这么多,看了这么多。你们发现没,说到底就是第一次put 创建了一个Node<K,V>类型的数组并且这个数组的长度是16。是不是和ArrayList有点像啊?ArrayList 初始化创建的数组大小是10
添加第一个元素后图:
下面继续添加
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {//hash:3367 key:"K2" value:"V2" onlyIfAbsent:false evict:true
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//p:null n:16 i:7
tab[i] = newNode(hash, key, value, null);//tab[i]:tab[7] newNode(hash:3367 key:"K2" value:"V2" null)
else {
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;
}
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;//modCount:2
if (++size > threshold)
resize();
afterNodeInsertion(evict);//不做处理
return null;
}
添加第二个元素后图:
如果出现下标相同的元素怎么存放呢?这里就要用到我们之前Node对象里面的 next 变量了。
下面我们来看看源码:
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)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {//如果出现 tab[i = (n - 1) & hash] 不为null 则进入else
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;
}
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;
}
p.next = newNode(hash, key, value, null);// 这句话是关键
画个图给大家看一下。
如果 i = (n - 1) & hash 结果是11 而源数组tab[11] 有引用,那么就会把Node对象的next 节点指向这个新的Node对象。
这样就变成一个单向链表了。
这里也是很重要的一句话:
static final int TREEIFY_THRESHOLD = 8;
//中间代码省略
if (binCount >= TREEIFY_THRESHOLD - 1) //当单向链表长度到8时,将链表转化为红黑树来处理
treeifyBin(tab, hash);//把链表转化为红黑树
再补一个知识点,为什么当链表长度等于8的时候才转化成红黑树呢?
这里面设计到一个统计学知识,叫做泊松分布
。泊松分布是什么?是一种统计与概率学里常见到的离散机率分布。
在我们hashmap里面源码注释也给你说了这么一回事。
按照他这个公式来(exp(-0.5) * pow(0.5, k) / factorial(k))
意思就是,一般情况下,0.75的load factor,HashMap每个slot可能存在值的几率是0.5,每个HashMap的slot下的Entry个数符合泊松分布,我们只要把Entry下个数k带入泊松分布的公式 (exp(-0.5) * pow(0.5, k) / factorial(k)),就可以得到平常情况(非恶意构造key)下list转tree的概率,如果长度达到8时才转,这种情况发生概率是0.00000006
。够低了,所以这个阈值定的8。
所以一般情况下红黑树是很少很少用到的。