源码头注释
hashmap是哈希表基于Map接口的实现。提供了所有可选map的集合。允许key和value都为空。除去HashMap允许key和value为空以及不同步的特点,其他都等价于Hashtable。该类不保证映射的顺序,也不保证随着时间的推移,映射是一致不变的。
假设hash()将元素均匀的分散在桶里,该实现可以为get()和put()提供一个恒定的时间性能。集合视图迭代遍历所需要的时间与hashmap实例的容量(桶的数量)加上映射的数量成正比。如果迭代的性能很重要,就不要把初始容量设太高或把负载因子设太低。
hashmap的实例有两个影响性能的参数:初始容量和负载因子。容量是哈希表所拥有的的桶的数量,初始容量是哈希表在创建时的容量。负载因子是衡量哈希表在扩容前所允许有多满。当哈希表中的条目数超过负载因子与容量的乘积时,哈希表需要rehashed,使hash表有当前桶的两倍。
一般来说,loadfactor=0.75时可以在时空上提供一个良好的性能。较高的值会减少空间的开销但是会增加查找的成本。设置initialCapacity时应设置预期的条目数和loadfactor以减少rehash的次数。如果初始容量大于当前最大条目数*负载因子,就不会进行rehash操作
如果hashmap实例中存储太多映射,创建足够大的映射会比让它根据需要自动rehash来增长表 更高效。使用许多具有相同hashCode()返回值的键会降低哈希表中任何方法的性能。当键是Comparable时,此类可以使用比较顺序来打破平局。
需要注意hashmap的实现并不是同步的。多线程同时操作一个hashmap,至少一个线程在结构上修改hashmap,必须在外部进行同步操作。(增加或删除一个或多个节点是结构上的修改操作,仅仅改变一个key的value值已经不是结构上的修改操作。)一般是通过自然封装在map中的一些对象来实现同步操作。
如果没有这样这些帮助同步的对象,需要使用Collections,synchronizedMap()来实现同步。这是在创建时阻止意外的不同步访问map的最好方法。
Map m = Collections.synchronizedMap(new HashMap(…))
这个集合视图方法返回的所有的迭代器都是fail-fast:如果在迭代器创建后map被结构性的修改,除了使用迭代器自身的移除方法,其他无论什么方法都会抛出@ConcurrentModificationException。因此,并发修改方面,迭代器出错的快速并干净,而不是在不确定的时间里随意出错。
fail-fast行为的迭代器不能被保证,一般来说,不可能在不同步并发的修改中做出硬保证。ConcurrentModificationException会尽可能被失败的迭代器快速抛出。因此,编写于一个期待通过异常检测正确性的程序是错误的,fast-fail的行为应该被用于发现错误。
该映射通常作为桶式的哈希表,但是当桶太大,经常会被转换为TreeNodes式的箱,每个结构类似于Java.util.TreeMap。大多数方法使用正常的桶,但是应用时依赖于TreeNode方法(只需检查各节点的实例)。TreeNodes的通需要像其他一样被转换并应用,但是当节点很多时额外支持更快的查询。然而,因为大多数桶使用过程中节点数量不会很多,方法中检查树型桶的存在会耽误时间
基本元素
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 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;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and 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.)
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
对于Node<K,V>[] table;
final int hash;
final K key;
V value;
Node<K,V> next;
默认的初始容量为什么一定是2的幂
hashmap计算存储位置时,使用了(n-1)&hash。当容量为2的幂次方,n-1的二进制全为1,位运算时可以充分散列,避免不必要的哈希冲突。包括扩容也是2倍扩容。
loadFactor为什么一定是0.75
loadfactor=0.75时可以在时空上提供一个良好的性能。较高的值会减少空间的开销但是会增加查找的成本。设置initialCapacity时应设置预期的条目数和loadfactor以减少rehash的次数。
核心方法
putVal()
/**
* Implements Map.put and related methods.
*
* @param hash hash for key hash=hash(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;
//table数组是链表的整体结构 在table数组的各个元素中包括了链表/红黑树
if ((tab = table) == null || (n = tab.length) == 0)
//1. 数组此时没有元素,需要进行数组的初始化(resize操作
n = (tab = resize()).length;
//使用(tab.length-1)&(h=(key.hashCode())^(h>>16)确定桶的位置
if ((p = tab[i = (n - 1) & hash]) == null)
//2.1 如果tab[i]为空 可以直接在table[i]对应的链表中插入节点
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//2.2 table[i]值不相同,而key值相同 把该节点赋值给e 等待后续操作
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
//2.3如果要插入的结点是树节点
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);
//2.4 如果当前节点数量比树的阈值(8)相等
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//需要树化该桶hash值所对应的链表
treeifyBin(tab, hash);
break;
}
//如果key已经存在 那么将新节点赋值 在最后做统一的value覆盖
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 2.3 如果e不为空 存在映射 就将value值覆盖
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//3. 结构修改的次数增加(便于fast-fail
++modCount;
//4. 判断当前尺寸是否大于阈值 (阈值=容量*负载因子
if (++size > threshold)
//4.1 扩容操作
resize();
afterNodeInsertion(evict);
return null;
}
hash()
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
如何确定hashmap中插入节点的桶的位置
- 取得key的hash值,不是简单的取hashcode。而是 hash=(h = key.hashCode()) ^ (h >>> 16)。
- 得到桶的位置 i = (n-1)&hash。
计算哈希值时为什么一定要右移十六位
尽可能打乱hashCode真正参与运算的低16位,让元素在hashmap中分布更均匀。
h>>>16表示无符号右移16位,取int类型的一半,将二进制数对半切开。
resize
/**
* 既是初始化table数组操作 又是加倍大小操作
* 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;
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
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);
}
//计算新的阈值上限
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//修改原table[i]中节点排列情况
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
//判断的根本条件是 e.hash & (newCap - 1)
//newCap是oldCap的二倍 多了一位
//只需判断节点的原hash值与newCap最高位对应的那位bit是1还是0
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;
//是0不变
newTab[j] = loHead;
}
if (hiTail != null) {
//是1 原索引需要加上oldCap
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
参考链接: 添加链接描述