Module  java.base
Software package  java.util

Class 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 inHashMapIn 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 inHashMapIn 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 useCollections.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 ownremoveExcept 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 basisConcurrentModificationException 。 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
    • 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
      void clear()
      Removes all mappings from this map.
      Object clone()
      Return thisHashMapA shallow copy of the instance: the keys and values themselves are not cloned.
      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 )。
      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 enter it into this mapping, unlessnull 。
      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)
      If this map contains a mapping for the specified key, then returnstrue 。
      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 the mappings contained in this mapSetview.
      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 。
      boolean isEmpty()
      Returns true if this map contains no key-value mappings.true 。
      Set<K> keySet()
      Returns the keys contained in this mapSetview.
      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.
      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 remove​(Object key)
      Removes the mapping for the specified key from this map if it is present.
      int size()
      Returns the number of key-value mappings in this map.
      Collection<V> values()
      Returns the values contained in this mapCollectionview.
    • 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.
        Specified by:
        sizeIn the interfaceMap<K,​V>
        Override:
        sizeClassAbstractMap<K,​V>
        Result
        The number of key-value mappings in this map
      • isEmpty

        public boolean isEmpty()
        Returns true if this map contains no key-value mappings.true 。
        Specified by:
        isEmptyIn the interfaceMap<K,​V>
        Override:
        isEmptyClassAbstractMap<K,​V>
        Result
        trueIf this map contains no key-value mappings
      • 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 keykTo 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 Valuenull Not 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 valuekey, ornullif there is no mappingkey 。 (A nullThe 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 nokeymapping, then withkeyornullthe associated previous value. (A nullThe 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.
        Specified by:
        clearIn the interfaceMap<K,​V>
        Override:
        clearin the courseAbstractMap<K,​V>
      • 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.
        Specified by:
        keySetIn the interfaceMap<K,​V>
        Override:
        keySetIn classAbstractMap<K,​V>
        Result
        The set view of the keys contained in this map
      • 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.
        Specified by:
        valuesIn the interfaceMap<K,​V>
        Override:
        valuesin class.AbstractMap<K,​V>
        Result
        A view of the values contained in this map
      • 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.
        Specified by:
        entrySetIn the interfaceMap<K,​V>
        Result
        A set view of the mappings contained in this map
      • 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 returnsnull, 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 mapMap<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 returnsnull, 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:
           map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg)) 
        (methodmerge()Usually easier to use for such purposes.)

        If the remapping function returnsnull, 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 throwConcurrentModificationException 。

        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 returnsnull, 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
      • clone

        public Object clone()
        Return thisHashMapA shallow copy of the instance: the keys and values themselves are not cloned.
        Override:
        cloneClassAbstractMap<K,​V>
        Result
        A shallow copy of this map
        See also:
        Cloneable