一. 问题背景
在看Java面试题的时候看到HashMap的问题比较多,所以学习了HashMap的实现原理。使用源码分析加百度搜索博客等等综合分析。本人小白,做此笔记仅供自己参考,有不恰当的地方请指出。
二. 储备知识
了解以下知识有助于更好地理解HashMap的结构。如下:
HashMap怎么分配数组下标?答:使用hash函数,详情下面会讲述。
三. HashMap的成员变量
打开idea,创建一个java工程,按两下shift,搜索HashMap
,选择源码的文件。点击左下角的structure
,拉到最下面,可以看到HashMap的成员变量。如下:
四. 源码分析
如下:首先看到HashMap继承了AbstractMap<K, V>
,实现了Map<K, V>
接口,Cloneable接口,Serializable
接口。由此可以看出HashMap能被序列化。(被标注了transient的成员变量不能被Serializable接口序列化)
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
4.1 静态常量
默认初始容量: 将1左移4位,即2^4=16,注释中写了MUST be a power of two
,意思是容量值必须是2的幂次方,为什么有这个要求?因为容量值将参与数组下标的计算。(后面会详细讲述)
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
最大容量: 2^30
MUST be a power of two <= 1<<30
限制了容量值必须<=2^30
/**
* 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中的元素达到(负载因子*容量值),则会进行扩容。比如容量值为16,负载因子为0.75,当hashmap中元素达到12时会进行扩容。扩大的容量为原来的2倍(即旧容量值左移1位)
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
树化阈值: 桶的链表中元素>=8,则将链表转换为红黑树。转为树的大前提条件是hashmap中的元素个数不小于64。
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
非树化阈值: 桶的链表中元素<=6,则将红黑树转换为链表。
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
树化阈值的最小容量: 链表转为树的大前提条件是hashmap中的元素个数不小于64。
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
4.2 成员变量
table数组: 是Node<K, V>类型的数组,hashmap用来存储键值对。首次使用时会被初始化。分配内存时,长度必须是2的幂次方。有时候也容许在启动的时候长度为0。被transient修饰,不能被Serializable序列化。
/**
* 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.)
*/
transient Node<K,V>[] table;
键值对的集合: 是Set<Map.Entry<K,V>>类型。Entry是一个接口
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
键值对个数: 指hashmap中存了多少对键值
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
修改操作的次数: 每做一次修改操作,都会加1。这是防止多线程并发出问题。
/**
* 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 load factor for the hash table.
*
* @serial
*/
final float loadFactor;
阈值: hashmap中的键值对达到多少时,需要扩容。threshold=capacity * load factor。比如capacity=16,loadFactor=0.75,那么在hashmap的table数组中有12位置被占用的时候会进行扩容。扩大的容量为原来的2倍。(因为是旧容量左移1位)
/**
* 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.)
int threshold;
4.3 HashMap
的构造方法
hashmap有四个构造方法,如下:
可以总结一句话:没有指定负载因子、容量值,都是采用默认的。特例是形参为map的构造方法是根据map的大小确定容量的。
HashMap(): 指定了负载因子。其他都是用默认的。
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
HashMap(int initialCapacity, float loadFactor): 检查容量值是否超过最大容量值、是否小于0。检查负载因子是否符合格式。将指定的负载因子赋给成员变量loadFactor
,将指定的容量值转成最接近且比它大的2幂次方(比如指定容量值是9,使用tableSizeFor(initialCapacity)
转成16;),然后赋给成员变量threshold
。
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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);
}
//将容量变为最接近的二次方幂。可以自行测试,假设cap=7,则得到方法返回值为8;cap=9,得到返回值16。
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
HashMap(int initialCapacity): 指定了容量值,其他没有指定的则使用默认。然后调用上面讲到的HashMap(int initialCapacity, float loadFactor)
构造方法
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
HashMap(Map<? extends K, ? extends V> m): 使用默认的负载因子,容量值根据入参map决定(必须是2的幂次方)
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
4.4 HashMap的静态内部类——Node<K, V>
这是HashMap用来存储键值对的,HashMap有一个transient Node<K,V>[] table;
。该类的成员变量和构造方法如下:
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;
}
4.5 HashMap的put方法
如下是HashMap的put方法,从注释可以看到A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>
证明HashMap是支持null作为键的。put方法中调用了puVal()方法,我们点进去看看有什么
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
可以看到putVal()方法返回的是一个V(即键值对的值)。如下:
/**
* 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.
* @return previous value, or null if none
*/
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 {
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;
}
为了分析putVal()方法,我们做如下操作:
HashMap<String, String> map = new HashMap<String, String>();
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
- 首先使用空参构造器new了一个HashMap,因为使用空参构造,所以所有的成员变量都使用默认值(比如使用默认的容量,默认的负载因子)。所以当前map实例中的table变量是null的,没有指向任何一个地方。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
- 然后map调用了put方法,前面介绍put()方法,它是调用putVal()方法。如下:
- resize()方法如下:
- 经过上面的分析resize()方法用来初始化map实例的table数组。继续分析putVal()方法。如下:
为什么用(table数组的长度-1) 和 (hash) 做&运算呢? 我们看看hash()方法是怎么实现的,如下:
- hashCode()方法如下:
- 继续分析hash()方法。我们假设"k1".hashCode()得到的是1234123,1234123的二进制是
100101101010011001011
,因为int整型是4个字节,所以有32位,所以123的二进制是00000000000100101101010011001011
,将它右移16位得到00000000000000000000000000010010
- 返回到putVal()方法中,继续分析 为什么用(table数组的长度-1) 和 (hash) 做&运算呢?
jdk1.7中这个是一个用来计算table数组下标的方法(即计算实际的存储位置,即桶号)。
为了方便描述,下面用n-1代表(table数组的长度-1)
table数组的长度被限制成了2的幂次方,所以(table数组长度-1)的二进制每一位都是1, 比如长度为16,16-1=15,15的二进制为1111。因此当与每一位都为1的数做&运算,只有当另外一操作数的位上为1时,结果的位上才能得到1。 因此如果n=16,则n-1=15。那么table数组最大的下标为15。不管hash有多大,都不会大于15。也就不会数组越界
为什么不用取余%操作?
- hash计算得到的值很大,取余的话,基本都落到最后一个桶内,分布不均匀
- java的%、/操作都比&运算的效率低
- 继续分析putVal()方法,如下: