本文以jdk1.8为例分析HashMap,不考虑和以前版本的比较。
1、成员变量
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
HashMap的默认大小值(也即是16)。其中注释提到了,大小必须是2的次幂,原因简单来说是为了防止哈希冲突,保证分布均匀,详细解释可以参考这篇文章https://blog.csdn.net/zjcjava/article/details/78495416 这里只做一个文字说明:
hashmap是以数组存储,数组的索引是存储的key的hash值和(数组大小-1)求与运算,假设hashmap的大小是2的次幂,那么这个值减1的二进制后几位上的值都会是1,这就保证了它和key的hash值求与运算的时候,key的hash值后几位是保持不变的,这样,只要输入的key值是均匀的,那么最后在hashmap中存储的结果其分布就是均匀的。
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
DEFAULT_LOAD_FACTOR 装载因子,默认为0.75,指的是当使用空间大于容量的0.75倍时,就会进行扩容,至于为什么会是0.75这个值,可自行百度或参考https://www.jianshu.com/p/64f6de3ffcc1。
/**
* 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;
TREEIFY_THRESHOLD 涉及到jdk对hashmap进行的一次优化:hashmap底层以数组存储,而每个数组元素又以链表的形式存在,如果链表的长度大于TREEIFY_THRESHOLD 这个值,链表结构就会转化为树结构。
2、静态内部类
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
}
定义了hashmap的存储单元,也即是底层数组的存储类型。
3、构造函数
/**
* 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);
}
initialCapacity参数,初始容量,需要注意的是这个参数并不是用来初始化hashmap底层数组大小的,而是作为一个阈值:当hashmap中的元素个数大于这个值的时候,数组就会进行扩容(这和上面提到的DEFAULT_LOAD_FACTOR参数作用并不矛盾,DEFAULT_LOAD_FACTOR参数也是用来计算threshold值的)。
4、主要方法
4.1 hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
因为底层数组的下标是由key(hash)值的低位决定的,所以hashmap提供的hash方法中,将高位的值移至低位(int类型32个字节,移动16位正好移动一半) ,然后与原值求异或,这样就保证了得到的值的低位同时具有原来key值的高位和低位的特征。
4.2 get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
首先调用hash方法求出key的hash值,然后调用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) {
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;
}
getNode方法中,首先根据传入的hash值得到数组索引:(n - 1) & hash(之所以索引这样计算,是为了尽量保证存储分布均匀),找到对应数组中的元素,然后遍历元素的每个节点,返回正确的值。其中链表的遍历和树是分开(数组的每个成员要么是链表结构,要么是树结构,不会有其他的结构),链表的遍历比较简单,利用do…while循环,依次找下去即可;树的遍历是首先找到根节点,然后从上向下寻找(树的这一部分稍后讲解)。
4.3 containsKey方法
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
依旧是调用的getNode方法。