- java.lang.Object
-
- java.util.AbstractMap<K,V>
-
- java.util.HashMap<K,V>
-
- Parameter Type
-
K- The key type maintained by this mapping -
V- The type of mapped values
- All implemented interfaces
-
Serializable,Cloneable,Map<K,V>
- Known direct subclasses:
-
LinkedHashMap,PrinterStateReasons
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
based on a hash tableMapimplementation of the interface. This implementation provides all optional map operations and permitsnullValue andnullKey. (HashMapthe class is roughly equivalent toHashtable, except that it is unsynchronized and permits null values.) This class makes no guarantees as to the order of the map; In particular, it does not guarantee that the order will remain unchanged over time.This implementation provides basic operations (
getandput) provides constant-time performance, assuming the hash function disperses elements properly among the buckets. Iteration over collection views needs to be synchronized withHashMapTime proportional to the capacity (number of buckets) of the instance plus its size (number of key-value mappings). Therefore, if iteration performance is important, it is very important not to set the initial capacity too high (or the load factor too low).HashMapThe instance has two parameters that affect its performance:initial capacityandLoad Factor 。 CapacityIs the number of buckets in the hash table; the initial capacity is simply the capacity at the time the hash table is created. load factorIt 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 will beAgainRehashes (i.e., rebuilds the internal data structure) so that the hash table has approximately twice the number of buckets.As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values reduce space overhead but increase lookup cost (reflected in
HashMapIn most operations of the class, includinggetandput)。 When setting its initial capacity, the expected number of entries in the map and its load factor should be considered in order to minimize the number of rehashing operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operation will occur.If you want to store multiple mappings in
HashMapIn this case, creating a map with a sufficiently large capacity will allow the map to store more efficiently, rather than performing automatic rehashing as needed to expand the table. Note that using the samehashCode()Many keys are a reliable way to slow down the performance of any hash table. To improve the effect, when the key isComparablewhenSuch classes can use the comparison order between keys to help break ties.Please 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, thenRequiredSynchronize externally. (StructuremodifyYesaddorDeleteaor multiple映射anyOperation;only更updateandExample已containsofKeycloseunitevalue ofis notStructuremodify。)这通常Throughsame步自butEncapsulation映射of某itemsObjectto complete. 。 If such an object does not exist, you should use
Collections.synchronizedMapmethods that “wrap” a map. This is best done at creation time to prevent accidental unsynchronized access to the map:Map m = Collections.synchronizedMap(new HashMap(...));All iterators returned by this class's "collection view methods" arefail-fast: If the map is structurally modified at any time after the iterator is created, except through the iterator's own
removeExcept through the method, the iterator will throwConcurrentModificationException。 Therefore, in the case of concurrent modification, the iterator fails fast and cleanly, rather than risking arbitrary, non-deterministic behavior at an unspecified time in the future.Please note that the fail-fast behavior of iterators cannot be guaranteed, because in general, it is impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw on a best-effort basis
ConcurrentModificationException。 Therefore, it is incorrect to write programs that depend on this exception to ensure their correctness:The fail-fast behavior of an iterator should be used only to detect bugs.This type isJava Collections Frameworkthe member.
- Starting from the following version:
- 1.2
- See also:
-
Object.hashCode(),Collection,Map,TreeMap,Hashtable, Serialized Form
-
-
Nested Class Summary
-
Nested classes/interfaces declared in class java.util.AbstractMap
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
-
-
Constructor Summary
Constructor Constructor Description HashMap()Constructs an empty map with the default initial capacity (16) and the default load factor (0.75).HashMap。HashMap(int initialCapacity)Constructs an empty [map] with the specified initial capacity and the default load factor (0.75).HashMap。HashMap(int initialCapacity, float loadFactor)Constructs an empty map with the specified initial capacity and load factor.HashMap。HashMap(Map<? extends K,? extends V> m)constructs a newHashMap, whose mapping with the specifiedMapSame.
-
Method Summary
All methods Instance Methods Specific Methods Variables and types Methods Description voidclear()Removes all mappings from this map.Objectclone()Return thisHashMapA shallow copy of the instance: the keys and values themselves are not cloned.Vcompute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (if there is no current mapping,null)。VcomputeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)If the specified key has not yet been associated with a value (or mapped tonull), then attempts to compute its value using the given mapping function and enter it into this mapping, unlessnull。VcomputeIfPresent(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.booleancontainsKey(Object key)If this map contains a mapping for the specified key, then returnstrue。booleancontainsValue(Object value)Returns true if this map maps one or more keys to the specified value.true。Set<Map.Entry<K,V>>entrySet()Returns the mappings contained in this mapSetview.Vget(Object key)Returns the value to which the specified key is mapped, or returns [null] if this map contains no mapping for the key.null。booleanisEmpty()Returns true if this map contains no key-value mappings.true。Set<K>keySet()Returns the keys contained in this mapSetview.Vmerge(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.Vput(K key, V value)Associates the specified value with the specified key in this map.voidputAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map.Vremove(Object key)Removes the mapping for the specified key from this map if it is present.intsize()Returns the number of key-value mappings in this map.Collection<V>values()Returns the values contained in this mapCollectionview.-
Methods declared in class java.util.AbstractMap
equals, hashCode, toString
-
Methods declared in interface java.util.Map
equals, forEach, getOrDefault, hashCode, putIfAbsent, remove, replace, replace, replaceAll
-
-
-
-
Constructor Details
-
HashMap
public HashMap(int initialCapacity, float loadFactor)Constructs an empty map with the specified initial capacity and load factor.HashMap。- Parameter
-
initialCapacity- initial capacity -
loadFactor- load factor - Exception
-
IllegalArgumentException- If the initial capacity is negative or the load factor is non-positive
-
HashMap
public HashMap(int initialCapacity)
Constructs an empty [map] with the specified initial capacity and the default load factor (0.75).HashMap。- Parameter
-
initialCapacity- initial capacity. - Exception
-
IllegalArgumentException- If the initial capacity is negative.
-
HashMap
public HashMap()
Constructs an empty map with the default initial capacity (16) and the default load factor (0.75).HashMap。
-
HashMap
public HashMap(Map<? extends K,? extends V> m)
constructs a newHashMap, whose mapping with the specifiedMapSame.HashMapCreated with the default load factor (0.75) and sufficient capacity to hold the specifiedMapThe initial capacity of the map.- Parameter
-
m-mThe mapping to be placed in this map - Exception
-
NullPointerException- If the specified map is null
-
-
Method Details
-
size
public int size()
Returns the number of key-value mappings in this map.
-
isEmpty
public boolean isEmpty()
Returns true if this map contains no key-value mappings.true。
-
get
public V get(Object key)
Returns the value to which the specified key is mapped, or returns [null] if this map contains no mapping for the key.null。More formally, if this map contains a mapping from key
kTo valueva mapping such that(key==null ? k==null : key.equals(k)), then this method returnsv; otherwise returnsnull。 (There can be at most one such mapping.)Return Value
nullNot necessarilyRepresents a mapping that does not contain keys; The map may also explicitly map keys to.null。 You can usecontainsKeyoperation to distinguish between these two cases.- Specified by:
-
getIn the interfaceMap<K,V> - Override:
-
getClassAbstractMap<K,V> - Parameter
-
key- The key whose associated value is to be returned - Result
- The value to which the specified key is mapped, or, if this map contains no mapping for the key,
null - See also:
-
put(Object, Object)
-
containsKey
public boolean containsKey(Object key)
If this map contains a mapping for the specified key, then returnstrue。- Specified by:
-
containsKeyIn the interfaceMap<K,V> - Override:
-
containsKeyIn classAbstractMap<K,V> - Parameter
-
key- The key whose presence in this map is to be tested - Result
-
trueIf this map contains a mapping for the specified key.
-
put
public V put(K key, V value)
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.- Specified by:
-
putIn the interfaceMap<K,V> - Override:
-
putin class.AbstractMap<K,V> - Parameter
-
key- The key associated with the specified value -
value- The value associated with the specified key - Result
-
associated with the previous value
key, ornullif there is no mappingkey。 (AnullThe return can also represent the mapping previously associated.nullandkey)。
-
putAll
public void putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.- Specified by:
-
putAllIn the interfaceMap<K,V> - Override:
-
putAllIn classAbstractMap<K,V> - Parameter
-
m- The mapping to be stored in this map - Exception
-
NullPointerException- If the specified map is null
-
remove
public V remove(Object key)
Removes the mapping for the specified key from this map if it is present.- Specified by:
-
removeIn the interfaceMap<K,V> - Override:
-
removeIn classAbstractMap<K,V> - Parameter
-
key- The key whose mapping is to be removed from the map - Result
-
if there is no
keymapping, then withkeyornullthe associated previous value. (AnullThe return can also represent the mapping previously associated.nullandkey)。
-
clear
public void clear()
Removes all mappings from this map. After this call returns, the mapping will be empty.
-
containsValue
public boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.true。- Specified by:
-
containsValueIn the interfaceMap<K,V> - Override:
-
containsValueClassAbstractMap<K,V> - Parameter
-
value- The value whose presence in this map is to be tested - Result
-
trueIf this map maps one or more keys to the specified value
-
keySet
public Set<K> keySet()
Returns the keys contained in this mapSetview. The set is backed by the map, so changes to the map are reflected in the set, and vice versa. If the map is modified while iterating over the collection (except through the iterator's ownremoveoperation), the result of the iteration is undefined. This set supports element removal, which removes the corresponding mapping from the map, viaIterator.remove,Set.remove,removeAll,retainAll, andclearoperation. it does not supportaddoraddAlloperation.
-
values
public Collection<V> values()
Returns the values contained in this mapCollectionview. The collection is backed by the map, so changes to the map will be reflected in the collection, and vice versa. If the map is modified while iterating over the collection (except through the iterator's ownremoveoperation), the result of the iteration is undefined. This collection supports element removal, i.e., the corresponding mapping from the map, viaIterator.remove,Collection.remove,removeAll,retainAllandclearoperation. it does not supportaddoraddAlloperation.
-
entrySet
public Set<Map.Entry<K,V>> entrySet()
Returns the mappings contained in this mapSetview. The set is backed by the map, so changes to the map are reflected in the set, and vice versa. If the map is modified while iterating over the collection (except through the iterator's ownremoveoperation, or on the map entries returned by the iteratorsetValueoperation), the result of the iteration is undefined. This set supports element removal, which removes the corresponding mapping from the map, viaIterator.remove,Set.remove,removeAll,retainAllandclearoperation. it does not supportaddoraddAlloperation.
-
computeIfAbsent
public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
If the specified key has not yet been associated with a value (or mapped tonull), then attempts to compute its value using the given mapping function and enters it into this map, unlessnull。If the mapping function returns
null, then no mapping is recorded. If the mapping 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 as the initial mapped value or memoized result, as in:map.computeIfAbsent(key, k -> new Value(f(k)));or implement a multi-value map
Map<K,Collection<V>>, each key supports multiple values:map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);The mapping function should not modify this map during computation.
If it is detected that the mapping function modified this map during computation, the method will throw on a best-effort basis.
ConcurrentModificationException。- Specified by:
-
computeIfAbsentIn the interfaceMap<K,V> - Parameter
-
key- The key associated with the specified value -
mappingFunction- The mapping function used to compute the value - Result
- The current (existing or computed) value associated with the specified key, or null if the computed value is null
- Exception
-
ConcurrentModificationException- If it is detected that the mapping function modified this map
-
computeIfPresent
public 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.If the remapping function returns
null, then remove the mapping. If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.The remapping function should not modify this map during the computation.
If the remapping function is detected to have modified this map during the computation, this method will throw on a best-effort basis.
ConcurrentModificationException。- Specified by:
-
computeIfPresentIn the interfaceMap<K,V> - Parameter
-
key- The key associated with the specified value -
remappingFunction- The remapping function used to compute the value - Result
- The new value associated with the specified key, or null if none
- Exception
-
ConcurrentModificationException- If it is detected that the remapping function modified this map
-
compute
public 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 (if there is no current mapping,null)。 For example, to create or appendStringmessage-to-value mapping:(methodmap.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))merge()Usually easier to use for such purposes.)If the remapping function returns
null, then the mapping is removed (or remains absent if it did not initially exist). If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.The remapping function should not modify this map during the computation.
If it is detected that the remapping function modifies this map during computation, the method will make a best effort to throw
ConcurrentModificationException。- Specified by:
-
computeIn the interfaceMap<K,V> - Parameter
-
key- The key associated with the specified value -
remappingFunction- The remapping function used to compute the value - Result
- The new value associated with the specified key, or null if none
- Exception
-
ConcurrentModificationException- If it is detected that the remapping function modified this map
-
merge
public 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. Otherwise, replace the associated value with the result of the given remapping function, or if the result isnullthen remove it. When combining multiple mapped values for a key, this method can be useful. For example, to create or appendString msgto value mapping:map.merge(key, msg, String::concat)If the remapping function returns
null, then remove the mapping. If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.The remapping function should not modify this map during the computation.
If the remapping function is detected to have modified this map during the computation, this method will throw on a best-effort basis.
ConcurrentModificationException。- Specified by:
-
mergeIn the interfaceMap<K,V> - Parameter
-
key- the key associated with the result value -
value- A 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 remapping function to recompute the value, if present - Result
- The new value associated with the specified key, or null if no value is associated with the key
- Exception
-
ConcurrentModificationException- If it is detected that the remapping function modified this map
-
-