所在包:java.util.HashMap<K,V>
K
- the type of keys maintained by this map(映射维护键的类型)V
- the type of mapped values(映射值类型)
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>,Cloneable,Serializable
基于哈希表实现的映射接口。
此实现提供所有可选的映射操作,并允许空值和空键。
(HashMap类大致相当于Hashtable,只是它是不同步的,并且允许为空。)该类不保证映射的顺序;
特别是,它不能保证订单在一段时间内保持不变。
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap 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)提供了稳定的时间性能,假设散列函数将元素适当地分散到各个bucket中。
集合视图的迭代需要与HashMap实例的“容量”(桶的数量)及其大小(键值映射的数量)成比例的时间。
因此,如果迭代性能很重要,那么不要将初始容量设置得太高(或负载因子太低)是非常重要的。
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity 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 load factor 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 rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
HashMap实例有两个影响其性能的参数:初始容量和负载因子。
容量是哈希表中的桶数,初始容量只是创建哈希表时的容量。
负载因子是一个度量哈希表在其容量自动增加之前允许的满度的度量。
当哈希表中的条目数超过负载因子和当前容量的乘积时,将对哈希表进行重新哈希(即重新构建内部数据结构),使哈希表的桶数大约是桶数的两倍。
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 HashMap class, including get and put). 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的初始容量时,应该考虑map中条目的期望数量及其负载因子,从而最小化rehash操作的数量。
如果初始容量大于条目的最大数量除以负载因子,则不会发生重排操作。
If many mappings are to be stored in a HashMap 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 hashCode()
is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable
, this class may use comparison order among keys to help break ties.
如果要将许多映射存储在HashMap实例中,那么使用足够大的容量创建映射将比根据需要执行自动散列来扩展表更有效地存储映射。
注意,使用具有相同hashCode()的多个键肯定会降低任何散列表的性能。
为了改善影响,当键是可比较的,这个类可以使用键之间的比较顺序来帮助打破联系。
Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must 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. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap
method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
注意,这个实现不是同步的。
如果多个线程同时访问一个散列映射,并且至少有一个线程从结构上修改了该映射,则必须在外部对其进行同步。
(结构修改是指任何增加或删除一个或多个映射的操作;仅仅更改与一个实例已经包含的键相关联的值并不是结构修改。)
这通常是通过在一些自然封装了映射的对象上进行同步来实现的。
如果不存在这样的对象,则应该使用集合“包装”映射synchronizedMap方法。
这最好在创建时完成,以防止意外的不同步访问映射:
Map m = Collections.synchronizedMap(new HashMap(...));
The iterators returned by all of this class‘s "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator‘s own remove method, the iterator will throw a 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.
这个类的所有“集合视图方法”返回的迭代器是快速失效的:如果在创建迭代器之后的任何时候,以任何方式(除了通过迭代器自己的删除方法)对映射进行结构修改,迭代器将抛出ConcurrentModificationException异常。
因此,在面对并发修改时,迭代器会快速而干净地失败,而不是在将来某个不确定的时间冒任意的、不确定的行为的风险。
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 ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
注意,不能保证迭代器的快速故障行为,因为通常来说,在存在非同步并发修改的情况下,不可能做出任何严格的保证。
故障快速迭代器在最大努力的基础上抛出ConcurrentModificationException。
因此,编写一个依赖于这个异常的正确性的程序是错误的:迭代器的快速故障行为应该只用于检测bug。
This class is a member of the Java Collections Framework.
该类是Java集合框架的成员。
Object.hashCode()
, Collection
, Map
, TreeMap
, Hashtable
, Serialized Form
Constructor and Description构造函数和描述 |
---|
HashMap()
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
使用默认初始容量(16)和默认负载因子(0.75)构造一个空HashMap。
|
HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
构造一个具有指定初始容量和缺省负载因子(0.75)的空HashMap。
|
HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial capacity and load factor.
构造具有指定初始容量和负载因子的空HashMap。
|
HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map.
使用与指定映射相同的映射构造新的HashMap。
|
Modifier and Type 修饰符和类型 | Method and Description 方法和描述 |
---|---|
void |
clear()
Removes all of the mappings from this map.
从该映射中删除所有映射。
|
Object |
clone()
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
返回此HashMap实例的浅拷贝:键和值本身没有被克隆。
|
V |
compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Attempts to compute a mapping for the specified key and its current mapped value (or
null if there is no current mapping).尝试为指定的键及其当前映射值计算映射(如果没有当前映射,则为null)。
|
V |
computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
If the specified key is not already associated with a value (or is mapped to
null ), attempts to compute its value using the given mapping function and enters it into this map unless null .如果指定的键尚未与值关联(或映射为null),则尝试使用给定的映射函数计算其值并将其输入到此映射中,除非为null。
|
V |
computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
如果指定键的值存在且非空,则尝试计算给定键及其当前映射值的新映射。
|
boolean |
containsKey(Object key)
Returns true if this map contains a mapping for the specified key.
如果此映射包含指定键的映射,则返回true。
|
boolean |
containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.
如果此映射将一个或多个键映射到指定的值,则返回true。
|
Set<Map.Entry<K,V>> |
entrySet()
Returns a
Set view of the mappings contained in this map.返回此映射中包含的映射的集合视图。
|
void |
forEach(BiConsumer<? super K,? super V> action)
Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
为映射中的每个条目执行给定的操作,直到处理完所有条目或操作引发异常。
|
V |
get(Object key)
Returns the value to which the specified key is mapped, or
null if this map contains no mapping for the key.返回指定键映射到的值,如果该映射不包含键的映射,则返回null。
|
V |
getOrDefault(Object key, V defaultValue)
Returns the value to which the specified key is mapped, or
defaultValue if this map contains no mapping for the key.返回指定键映射到的值,如果此映射不包含键的映射,则返回defaultValue。
|
boolean |
isEmpty()
Returns true if this map contains no key-value mappings.
如果此映射不包含键值映射,则返回true。
|
Set<K> |
keySet()
Returns a
Set view of the keys contained in this map.返回此映射中包含的键的集合视图。
|
V |
merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
如果指定的键尚未与值关联,或与null关联,则将其与给定的非空值关联。
|
V |
put(K key, V value)
Associates the specified value with the specified key in this map.
将指定值与此映射中的指定键关联。
|
void |
putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map.
将指定映射的所有映射复制到此映射。
|
V |
putIfAbsent(K key, V value)
If the specified key is not already associated with a value (or is mapped to
null ) associates it with the given value and returns null , else returns the current value.如果指定的键尚未与值关联(或映射为null),则将其与给定值关联并返回null,否则将返回当前值。
|
V |
remove(Object key)
Removes the mapping for the specified key from this map if present.
如果存在,则从此映射中删除指定键的映射。
|
boolean |
remove(Object key, Object value)
Removes the entry for the specified key only if it is currently mapped to the specified value.
仅当指定键当前映射到指定值时,删除指定键的项。
|
V |
replace(K key, V value)
Replaces the entry for the specified key only if it is currently mapped to some value.
仅当指定键当前映射到某个值时,才替换该键的项。
|
boolean |
replace(K key, V oldValue, V newValue)
Replaces the entry for the specified key only if currently mapped to the specified value.
仅当当前映射到指定值时,替换指定键的项。
|
void |
replaceAll(BiFunction<? super K,? super V,? extends V> function)
Replaces each entry‘s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
将每个条目的值替换为对该条目调用给定函数的结果,直到处理完所有条目或该函数抛出异常。
|
int |
size()
Returns the number of key-value mappings in this map.
返回此映射中的键值映射的数目。
|
Collection<V> |
values()
Returns a
Collection view of the values contained in this map.返回此映射中包含的值的集合视图。
|
从类 java.util.AbstractMap 继承的方法
从类 java.lang.Object 继承的方法
finalize, getClass, notify, notifyAll, wait, wait, wait
从接口 java.util.Map 继承的方法
public HashMap(int initialCapacity, float loadFactor)
initialCapacity
- the initial capacity初始容量loadFactor
- the load factor加载因子IllegalArgumentException
- if the initial capacity is negative or the load factor is nonpositive IllegalArgumentException
- 如果初始容量为负或者加载因子为非正public HashMap(int initialCapacity)
initialCapacity
- the initial capacity初始容量.IllegalArgumentException
- if the initial capacity is negative如果初始容量为负.
public HashMap()
public HashMap(Map<? extends K,? extends V> m)
m
- the map whose mappings are to be placed in this map.m
- 映射,其映射关系将存放在此映射中NullPointerException
- if the specified map is null 如果指定的映射为 null
public int size()
public boolean isEmpty()
public V get(Object key)
null
if this map contains no mapping for the key.null
。 More formally, if this map contains a mapping from a key k
to a value v
such that (key==null ? k==null : key.equals(k))
, then this method returns v
; otherwise it returns null
. (There can be at most one such mapping.)
更确切地讲,如果此映射包含一个满足 (key==null ? k==null : key.equals(k))
的从 k
键到 v
值的映射关系,则此方法返回 v
;否则返回 null
。(最多只能有一个这样的映射关系。)
A return value of null
does not necessarily indicate that the map contains no mapping for the key; it‘s also possible that the map explicitly maps the key to null
. The containsKey
operation may be used to distinguish these two cases.
返回 null
值并不一定 表明该映射不包含该键的映射关系;也可能该映射将该键显示地映射为 null
。可使用 containsKey
操作来区分这两种情况。
get
in interface Map<K,V>
get
in class AbstractMap<K,V>
key
- the key whose associated value is to be returned要返回其关联值的键null
if this map contains no mapping for the keynull
put(Object, Object)
public boolean containsKey(Object key)
containsKey
in interface Map<K,V>
containsKey
in class AbstractMap<K,V>
key
- The key whose presence in this map is to be tested要测试其是否在此映射中存在的键
public V put(K key,V value)
put
in interface Map<K,V>
put
in class AbstractMap<K,V>
key
- key with which the specified value is to be associated指定值将要关联的键value
- value to be associated with the specified key指定键将要关联的值
public void putAll(Map<? extends K,? extends V> m)
putAll
in interface Map<K,V>
putAll
in class AbstractMap<K,V>
m
- mappings to be stored in this map要在此映射中存储的映射关系NullPointerException
- if the specified map is null 如果指定的映射为 null
public V remove(Object key)
remove
in interface Map<K,V>
remove
in class AbstractMap<K,V>
key
- key whose mapping is to be removed from the map其映射关系要从映射中移除的键public void clear()
public boolean containsValue(Object value)
containsValue
in interface Map<K,V>
containsValue
in class AbstractMap<K,V>
value
- value whose presence in this map is to be tested要测试其是否在此映射中存在的值public Set<K> keySet()
Set
view of the keys contained in this map. Set
视图。public Collection<V> values()
Collection
view of the values contained in this map. Collection
视图。public Set<Map.Entry<K,V>> entrySet()
Set
view of the mappings contained in this map. Set
视图。public V getOrDefault(Object key,V defaultValue)
Map
defaultValue
if this map contains no mapping for the key.从接口复制的描述:Map映射
返回指定键映射到的值,如果此映射不包含键的映射,则返回defaultValue。
getOrDefault
in interface Map<K,V>
key
- the key whose associated value is to be returned要返回其关联值的键defaultValue
- the default mapping of the key键的默认映射defaultValue
if this map contains no mapping for the key public V putIfAbsent(K key,V value)
Map
null
) associates it with the given value and returns null
, else returns the current value.putIfAbsent
in interface Map<K,V>
key
- key with which the specified value is to be associated要与指定值关联的键value
- value to be associated with the specified key要与指定键关联的值null
if there was no mapping for the key. null
return can also indicate that the map previously associated null
with the key, if the implementation supports null values.) 与指定键关联的前一个值,如果没有该键的映射,则为null。
(如果实现支持null值,则null返回也可以指示以前将null与键关联的映射。)
public boolean remove(Object key,Object value)
Map
从接口复制的描述:Map映射
仅当指定键当前映射到指定值时,删除指定键的项。
public boolean replace(K key,V oldValue,V newValue)
Map
从接口复制的描述:Map映射
仅当当前映射到指定值时,替换指定键的项。
replace
in interface Map<K,V>
key
- key with which the specified value is associated与指定值关联的键oldValue
- value expected to be associated with the specified key预期与指定键关联的值newValue
- value to be associated with the specified key要与指定键关联的值true
if the value was replaced 如果值被替换,则为真public V replace(K key,V value)
Map
从接口复制的描述:Map映射
仅当指定键当前映射到某个值时,才替换该键的项。
replace
in interface Map<K,V>
key
- key with which the specified value is associated与指定值关联的键value
- value to be associated with the specified key将指定值与指定键关联的键null
if there was no mapping for the key. null
return can also indicate that the map previously associated null
with the key, if the implementation supports null values.) public V computeIfAbsent(K key,Function<? super K,? extends V> mappingFunction)
Map
null
), attempts to compute its value using the given mapping function and enters it into this map unless null
.If the function returns null
no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memoized result, as in:
如果函数返回null,则不记录映射。
如果函数本身抛出一个(未检查的)异常,则会重新抛出异常,并且不会记录任何映射。
最常见的用法是构造一个新对象作为初始映射值或默记结果,如:
map.computeIfAbsent(key, k -> new Value(f(k)));
Or to implement a multi-value map, Map<K,Collection<V>>
, supporting multiple values per key:
或者实现一个多值映射,map <K,Collection<V>>,每个键支持多个值:
map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);
computeIfAbsent
in interface Map<K,V>
key
- key with which the specified value is to be associatedmappingFunction
- the function to compute a valuepublic V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
Map
If the function returns null
, the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
如果函数返回null,则映射将被删除。
如果函数本身抛出一个(未检查的)异常,则会重新抛出异常,并且当前映射保持不变。
computeIfPresent
in interface Map<K,V>
key
- key with which the specified value is to be associated要与指定值关联的键remappingFunction
- the function to compute a value用来计算一个值的函数public V compute(K key,
BiFunction<? super K,? super V,? extends V> remappingFunction)
Map
null
if there is no current mapping). For example, to either create or append a String
msg to a value mapping: map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
(Method merge()
is often simpler to use for such purposes.)If the function returns null
, the mapping is removed (or remains absent if initially absent). If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
如果函数返回null,则映射将被删除(如果最初没有映射,则映射将保持为空)。
如果函数本身抛出一个(未检查的)异常,则会重新抛出异常,并且当前映射保持不变。
public V merge(K key,V value,BiFunction<? super V,? super V,? extends V> remappingFunction)
Map
null
. String msg
to a value mapping: map.merge(key, msg, String::concat)
If the function returns null
the mapping is removed.
If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.
如果函数返回null,则删除映射。
如果函数本身抛出一个(未检查的)异常,则会重新抛出异常,并且当前映射保持不变。
merge
in interface Map<K,V>
key
- key with which the resulting value is to be associated要将结果值与之关联的键value
- the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key将与与键关联的现有值合并的非空值,或者,如果没有与键关联的现有值或空值,则与键关联remappingFunction
- the function to recompute a value if present如果存在,重新计算值的函数public void forEach(BiConsumer<? super K,? super V> action)
Map
public void replaceAll(BiFunction<? super K,? super V,? extends V> function)
Map
replaceAll
in interface Map<K,V>
function
- the function to apply to each entry 应用于每个条目的函数public Object clone()
clone
in class AbstractMap<K,V>
Cloneable
原文:https://www.cnblogs.com/LinQingYang/p/12545623.html