版本
JDK8(JDK1.8)
HashMap源码重点
1.允许空值和空键。HashMap类大致相当于Hashtable,只是HashMap不同步并且允许空值
2.HashMap的实例有两个参数影响其性能:初始容量和负载系数,当存储键值对数大于
初始容量乘以负载系数,则会发生扩容,并重新计算哈希值,默认初始容量是16,负载系数为0.75,
最大容量为2的30次幂,负载系数 = 键值对数 / 容量
3.负载系数较高会减少空间开销,但会增加查找成本
4.具有相同hashCode() 的多个键会降低HashMap的性能,但可以通过实现Comparable接口,来比较进行排序,如果即具有相同hashCode()又没有实现Comparable接口,则会降低性能
5.HashMap不同步,所以多线程访问HashMap要在外面加上synchronized同步
6.Map m = Collections.synchronizedMap(new HashMap(…)),Collections类的synchronizedMap方法可以将一个新的HashMap包装成同步的
7.keySet() 获取键Set集合,values()获取值集合,entrySet() entry的Set集合,这三个方法获得的集合都与HashMap相联系,如果在使用这三个方法获得Set集合后,往Map中添加删除键值对,也会修改Set集合中的元素,并且修改Set集合也会影响到Map集合,但是仅限删除操作,添加会报错
8.使用keySet() 得到的迭代器iterator会在Map被修改后, 快速失效 ,抛出ConcurrentModificationException异常
9.HashMap通常由链表数组组成,如果数组中链表长度到达8个,则会将链表转换成红黑树,
如果转换成红黑树又删除一个节点,此时红黑树并不会重新变成链表 ,只有再删除一个节点,才会重新变成链表
10.如果HashMap容量小于64,但HashMap的链表长度到达8个,此时不会树化,而是先扩容,
HashMap部分源码
/**
* Hash table based implementation of the <tt>Map</tt> interface. This
* implementation provides all of the optional map operations, and permits
* <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
* class is roughly equivalent to <tt>Hashtable</tt>, except that it is
* unsynchronized and permits nulls.) This class makes no guarantees as to
* the order of the map; in particular, it does not guarantee that the order
* will remain constant over time.
* 基于哈希表的映射接口实现。这个实现提供了所有可选的映射操作,并允许空值和空键。
* HashMap类大致相当于Hashtable,只是它不同步并且允许空值。
* 此类不保证映射的顺序;特别是,它不能保证顺序在一段时间内保持不变。
*
* <p>This implementation provides constant-time performance for the basic
* operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
* disperses the elements properly among the buckets. Iteration over
* collection views requires time proportional to the "capacity" of the
* <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
* of key-value mappings). Thus, it's very important not to set the initial
* capacity too high (or the load factor too low) if iteration performance is
* important.
* 这个实现为基本操作(get和put)提供了恒定的时间性能,假设哈希函数将元素正确地分散在存储桶中。
* 对集合视图的迭代遍历需要与HashMap实例的“容量”(bucket数)加上其大小(键值映射数)成比例的时间。
* 因此,如果迭代遍历性能很重要,那么不要将初始容量设置得太高(或负载系数太低),这一点非常重要
*
*
* <p>An instance of <tt>HashMap</tt> has two parameters that affect its
* performance: <i>initial capacity</i> and <i>load factor</i>. The
* <i>capacity</i> is the number of buckets in the hash table, and the initial
* capacity is simply the capacity at the time the hash table is created. The
* <i>load factor</i> is a measure of how full the hash table is allowed to
* get before its capacity is automatically increased. When the number of
* entries in the hash table exceeds the product of the load factor and the
* current capacity, the hash table is <i>rehashed</i> (that is, internal data
* structures are rebuilt) so that the hash table has approximately twice the
* number of buckets.
* HashMap的实例有两个参数影响其性能:初始容量和负载系数。
* 容量是哈希表中的存储桶数,初始容量只是创建哈希表时的容量。
* 负载因子是在自动增加哈希表容量之前允许哈希表达到的满度的度量。
* 当哈希表中的条目数超过加载因子和当前容量的乘积时,
* 哈希表将被重新哈希(即,重建内部数据结构),
* 以已使哈希表的存储桶数大约是存储桶数的两倍。
*
* <p>As a general rule, the default load factor (.75) offers a good
* tradeoff between time and space costs. Higher values decrease the
* space overhead but increase the lookup cost (reflected in most of
* the operations of the <tt>HashMap</tt> class, including
* <tt>get</tt> and <tt>put</tt>). The expected number of entries in
* the map and its load factor should be taken into account when
* setting its initial capacity, so as to minimize the number of
* rehash operations. If the initial capacity is greater than the
* maximum number of entries divided by the load factor, no rehash
* operations will ever occur.
* 作为一般规则,默认负载系数(.75)提供了良好的性能时间和空间成本之间的权衡。
* 较高的值会减少空间开销,但会增加查找成本(反映在HashMap类的大多数操作中,包括get和put)。
* 在设置初始容量时,应考虑map中的预期条目数及其负载系数,
* 以尽量减少再哈希操作次数。如果初始容量大于最大键值对数除以负载系数,
* 则不会发生再哈希操作。
*
* <p>If many mappings are to be stored in a <tt>HashMap</tt>
* instance, creating it with a sufficiently large capacity will allow
* the mappings to be stored more efficiently than letting it perform
* automatic rehashing as needed to grow the table. Note that using
* many keys with the same {@code hashCode()} is a sure way to slow
* down performance of any hash table. To ameliorate impact, when keys
* are {@link Comparable}, this class may use comparison order among
* keys to help break ties.
* 如果要在HashMap实例中存储多个映射,
* 那么使用足够大的容量创建它将使映射的存储效率比让它根据需要自动重新哈希以增加容量更高。
* 请注意,使用具有相同hashCode()的多个键肯定会降低任何哈希表的性能。
* 为了改善影响,当键实现了Comparable接口,此类可以使用键之间的比较顺序来
* 帮助打破具有相同hashCode()的多个键的联系
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a hash map concurrently, and at least one of
* the threads modifies the map structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation
* that adds or deletes one or more mappings; merely changing the value
* associated with a key that an instance already contains is not a
* structural modification.) This is typically accomplished by
* synchronizing on some object that naturally encapsulates the map.
* 请注意,此实现是不同步的。如果多个线程同时访问哈希映射,
* 并且至少有一个线程在结构上修改了该映射,则必须在外部对其进行同步
* (结构修改是添加或删除一个或多个映射的任何操作;
* 仅更改与实例已包含的键关联的值不是结构修改。)
* 这通常通过在自然封装映射的某个对象上进行同步来实现。
* 即可以在外部使用synchronized让其同步
*
*
* If no such object exists, the map should be "wrapped" using the
* {@link Collections#synchronizedMap Collections.synchronizedMap}
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the map:<pre>
* Map m = Collections.synchronizedMap(new HashMap(...));</pre>
* 如果不存在这样的对象,则应使用Collections类下的synchronizedMap方法“包装”映射。
* 这最好在创建时完成,以防止对映射的意外非同步访问:
* Map m = Collections.synchronizedMap(new HashMap(...));
* 即使用Collections类下的synchronizedMap方法将新创建的HashMap变成同步的
*
*
*
* <p>The iterators returned by all of this class's "collection view methods"
* are <i>fail-fast</i>: if the map is structurally modified at any time after
* the iterator is created, in any way except through the iterator's own
* <tt>remove</tt> method, the iterator will throw a
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
* 这个类的所有“集合视图方法”返回的迭代器都是快速失效的:
* 如果在迭代器创建后的任何时候都以任何方式
* (除了通过迭代器自己的remove方法之外)修改了映射的结构,
* 迭代器将抛出ConcurrentModificationException 异常。
* 因此,在面对并发修改时,迭代器会快速、利索地失败,
* 而不是在将来的不确定时间冒着任意、不确定行为的风险。
*
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
* 请注意,无法保证迭代器的快速失效行为,
* 因为一般来说,在存在非同步并发修改的情况下,不可能做出任何硬保证。
* 快速失败迭代器会尽最大努力抛出ConcurrentModificationException。
* 因此,编写依赖于此异常的正确性的程序是错误的:迭代器的快速失败行为应该只用于检测bug。
*
*
*
*
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <K> the type of keys maintained by this map 此映射维护的键的类型
* @param <V> the type of mapped values 映射值的类型
*
* @author Doug Lea
* @author Josh Bloch
* @author Arthur van Hoff
* @author Neal Gafter
* @see Object#hashCode()
* @see Collection
* @see Map
* @see TreeMap
* @see Hashtable
* @since 1.2
*/
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
/*
* Implementation notes.
* 实现说明。
*
* This map usually acts as a binned (bucketed) hash table, but
* when bins get too large, they are transformed into bins of
* TreeNodes, each structured similarly to those in
* java.util.TreeMap. Most methods try to use normal bins, but
* relay to TreeNode methods when applicable (simply by checking
* instanceof a node). Bins of TreeNodes may be traversed and
* used like any others, but additionally support faster lookup
* when overpopulated. However, since the vast majority of bins in
* normal use are not overpopulated, checking for existence of
* tree bins may be delayed in the course of table methods.
* 此映射通常用作装箱(带扣)哈希表,但当容器变得太大时,
* 它们会转换为树节点的容器,每个容器的结构与java.util.TreeMap中的结构类似。
* 大多数方法尝试使用普通的链表节点容器,但是适用时中继到TreeNode方法(只需检查节点的实例)。
* 树节点的容器可以像其他任何容器一样被遍历和使用,但在数据过多时,还支持更快的查找。
* 然而,由于正常使用的绝大多数链表节点容器并不是数据过多,
* 在使用扩容方法的过程中,检查是否存在树节点的容器可能会延迟。
*
*
* Tree bins (i.e., bins whose elements are all TreeNodes) are
* ordered primarily by hashCode, but in the case of ties, if two
* elements are of the same "class C implements Comparable<C>",
* type then their compareTo method is used for ordering. (We
* conservatively check generic types via reflection to validate
* this -- see method comparableClassFor). The added complexity
* of tree bins is worthwhile in providing worst-case O(log n)
* operations when keys either have distinct hashes or are
* orderable, Thus, performance degrades gracefully under
* accidental or malicious usages in which hashCode() methods
* return values that are poorly distributed, as well as those in
* which many keys share a hashCode, so long as they are also
* Comparable. (If neither of these apply, we may waste about a
* factor of two in time and space compared to taking no
* precautions. But the only known cases stem from poor user
* programming practices that are already so slow that this makes
* little difference.)
* 树型箱(即,其元素均为树节点的箱)主要由hashCode排序,
* 但在hashCode相同的情况下,如果两个元素属于相同的类且实现了 Comparable接口,
* 则使用它们的compareTo方法用于排序
* (我们通过反射保守地检查泛型类型以验证这下面观点————请参见方法comparableClassFor)。
* 在提供最坏情况下的O(log n)操作时,当密钥具有不同的哈希或可排序时,树容器的额外复杂性是值得的,
* 因此,在偶然或恶意使用情况下,性能会下降,其中hashCode()方法返回的值分布不均,
* 以及多个键共享一个哈希代码的那些,只要它们也是可比较的(如果两者都不适用,与不采取预防措施相比,
* 我们可能在时间和空间上浪费大约两倍。但唯一已知的情况是由于糟糕的用户编程实践导致的,
* 这些实践已经非常缓慢,因此没有什么区别。)
*
*
*
* Because TreeNodes are about twice the size of regular nodes, we
* use them only when bins contain enough nodes to warrant use
* (see TREEIFY_THRESHOLD). And when they become too small (due to
* removal or resizing) they are converted back to plain bins. In
* usages with well-distributed user hashCodes, tree bins are
* rarely used. Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
*
* 由于TreeNode的大小大约是常规节点的两倍,
* 因此我们仅在容器包含足够的节点以保证使用时才使用它们(请参见TREEIFY_阈值)。
* 当它们变得太小时(由于移除或调整大小),它们会被转换回普通链表节点容器。
* 在使用分布良好的用户哈希代码时,很少使用树状容器。
* 理想情况下,在随机哈希码下,
* 容器中节点的频率遵循泊松分布
* 对于默认的大小调整阈值0.75,平均参数约为0.5,
* 但由于大小调整粒度,差异较大。忽略方差,
* 列表大小k的预期出现次数为(exp(-0.5)pow(0.5,k)/阶乘(k))。第一个值是:
0: 0.60653066
1: 0.30326533
2: 0.07581633
3: 0.01263606
4: 0.00157952
5: 0.00015795
6: 0.00001316
7: 0.00000094
8: 0.00000006
超过8个:不到一千万分之一
* 即哈希表是一个链表数组,这上面就是数组中链表的长度出现的概率
*
*
*
*
* The root of a tree bin is normally its first node. However,
* sometimes (currently only upon Iterator.remove), the root might
* be elsewhere, but can be recovered following parent links
* (method TreeNode.root()).
* 树容器的根通常是它的第一个节点。但是,有时(当前仅在Iterator.remove上),
* 根可能位于其他位置,但可以通过父链接(方法TreeNode.root())恢复。
*
*
* All applicable internal methods accept a hash code as an
* argument (as normally supplied from a public method), allowing
* them to call each other without recomputing user hashCodes.
* Most internal methods also accept a "tab" argument, that is
* normally the current table, but may be a new or old one when
* resizing or converting.
* 所有适用的内部方法都接受哈希值作为参数(通常由公共方法提供),
* 允许它们相互调用,而无需重新计算用户哈希值。
* 大多数内部方法也接受“tab”参数,通常是当前表,
* 但在调整大小或转换时可能是新的或旧的。
*
*
*
* When bin lists are treeified, split, or untreeified, we keep
* them in the same relative access/traversal order (i.e., field
* Node.next) to better preserve locality, and to slightly
* simplify handling of splits and traversals that invoke
* iterator.remove. When using comparators on insertion, to keep a
* total ordering (or as close as is required here) across
* rebalancings, we compare classes and identityHashCodes as
* tie-breakers.
* 当容器列表被树化、拆分或去树化,我们会保留它们具有相同的相对访问/遍历顺序
* (即字段Node.next)以更好地保留局部性,
* 并稍微简化对调用iterator.remove的拆分和遍历的处理。
* 当在插入时使用比较器时,为了在重新平衡过程中保持总顺序(或尽可能接近要求),
* 我们将类和识别hashCode作为连接断路器进行比较。
*
*
* The use and transitions among plain vs tree modes is
* complicated by the existence of subclass LinkedHashMap. See
* below for hook methods defined to be invoked upon insertion,
* removal and access that allow LinkedHashMap internals to
* otherwise remain independent of these mechanics. (This also
* requires that a map instance be passed to some utility methods
* that may create new nodes.)
*
* 普通模式与树模式之间的使用和转换是由于子类LinkedHashMap的存在而变得复杂。
* 请参阅下文,了解定义为在插入、移除和访问时调用的钩子方法,
* 这些钩子方法允许LinkedHashMap内部保持独立于这些机制
* (这还需要将映射实例传递给一些可能创建新节点的实用程序方法。)
*
*
*
* The concurrent-programming-like SSA-based coding style helps
* avoid aliasing errors amid all of the twisty pointer operations.
* 并行编程(如基于SSA的编码风格)有助于避免所有扭曲指针操作中的别名错误。
*/
/**
* The default initial capacity - MUST be a power of two.
* 默认初始容量-必须是2的幂。 即初始容量为16
*/
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.
* 最大容量,在两个带参数的构造函数中的任何一个隐式指定了更高的值时使用。
* 必须是2的幂<=1<<30。
* 即HashMap节点个数最大为2的30次方 1,073,741,824 十亿左右
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
* 构造函数中未指定时使用的负载因子。即初始负载因子为0.75
* 实际负载因子 = 节点个数 / 容量 如果实际负载因子大于设定的负载因子
* 会造成扩容,再哈希
*/
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.
* 使用树而不是列表的存储单元计数阈值,链表容器将元素添加
* 到至少具有这么多节点的容器时,容器将转换为树。
* 该值必须大于2,且应至少为8,
* 以符合从树容器移除元素收缩后转换链表容器的假设
*/
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.
* 存储期间取消(拆分)存储箱的存储箱计数阈值,调整大小操作。
* 应小于TREEIFY_阈值,最多6个网格,移除时进行收缩检测
* 即当链表数组中链表长度达到8后会转换成树结构,但是当转换
* 成树结构后又删除一个节点,那么节点数变为7,此时仍然不会
* 重新转换成链表结构,直到节点数变成6才会转换成链表结构
*/
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.
* 存储箱可树化的最小表容量。(否则,如果bin中的节点太多,则会调整表的大小。)
* 应至少为4*TreeFiy_阈值,以避免调整大小和树化阈值之间的冲突。
* 即如果HashMap容量小于64时,当链表数组中的链表长度超过8,此时
* 不会先进行树化,而是会对HashMap进行扩容
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
* 基本哈希节点(是一个链表结构),用于大多数条目(有关详细信息,
* 请参见下文TreeNode子类,并在LinkedHashMap中为其条目子类。)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}