95-30-020-java.util-Map

1.世界

在这里插入图片描述

1.拓扑图

在这里插入图片描述

2. 源码翻译

将键映射到值的对象。map不能包含重复的键;每个键最多可以映射到一个值。

这个接口代替了Dictionary类,它是一个完全抽象的类,而不是接口。

​ Map接口提供了三个集合视图,它允许将映射的内容视为一组键、值的集合或一组键值映射。map的order被定义为map集合视图上的迭代器返回其元素的顺序。一些map实现,比如TreeMap类,对它们的顺序做出了特定的保证;其他类,如HashMap类,则没有。

<p>Note: great care must be exercised if mutable objects are used as map
keys.  The behavior of a map is not specified if the value of an object is
changed in a manner that affects <tt>equals</tt> comparisons while the
object is a key in the map.  A special case of this prohibition is that it
is not permissible for a map to contain itself as a key.  While it is
permissible for a map to contain itself as a value, extreme caution is
advised: the <tt>equals</tt> and <tt>hashCode</tt> methods are no longer
well defined on such a map.

​ 注意:如果使用可变对象作为映射键,必须非常小心。如果以影响 = 比较的方式更改对象的值,而对象是映射中的键,则不指定映射的行为。这一禁令的一个特殊情况是,不允许地图将自己包含为键。虽然允许映射将自己包含为一个值,但是要特别注意 = 和hashCode方法不再在这样的映射上定义得很好。

<p>All general-purpose map implementation classes should provide two
"standard" constructors: a void (no arguments) constructor which creates an
empty map, and a constructor with a single argument of type <tt>Map</tt>,
which creates a new map with the same key-value mappings as its argument.
In effect, the latter constructor allows the user to copy any map,
producing an equivalent map of the desired class.  There is no way to
enforce this recommendation (as interfaces cannot contain constructors) but
all of the general-purpose map implementations in the JDK comply.

​ 所有通用map实现类都应该提供两个“标准”构造函数:一个创建空map的void(无参数)构造函数一个类型为 map 的单参数构造函数,该构造函数创建一个与其参数具有相同键值map的新map。实际上,后一个构造函数允许用户复制任何映射,生成所需类的等效映射。没有办法强制执行这个建议(因为接口不能包含构造函数),但是JDK中的所有通用映射实现都遵守这个建议。

<p>The "destructive" methods contained in this interface, that is, the
methods that modify the map on which they operate, are specified to throw
<tt>UnsupportedOperationException</tt> if this map does not support the
operation.  If this is the case, these methods may, but are not required
to, throw an <tt>UnsupportedOperationException</tt> if the invocation would
have no effect on the map.  For example, invoking the {@link #putAll(Map)}
method on an unmodifiable map may, but is not required to, throw the
exception if the map whose mappings are to be "superimposed" is empty.

​ 此接口中包含的“破坏性”方法,即修改其操作所在映射的方法,被指定为在该映射不支持操作时抛出UnsupportedOperationException。如果是这种情况,如果调用对映射没有影响,这些方法可以(但不是必须)抛出UnsupportedOperationException。例如,在不可修改的映射上调用{@link #putAll(Map)}方法,如果要“叠加”映射的映射为空,则可以抛出异常,但不是必须这样做。

<p>Some map implementations have restrictions on the keys and values they
may contain.  For example, some implementations prohibit null keys and
values, and some have restrictions on the types of their keys.  Attempting
to insert an ineligible key or value throws an unchecked exception,
typically <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.
Attempting to query the presence of an ineligible key or value may throw an
exception, or it may simply return false; some implementations will exhibit
the former behavior and some will exhibit the latter.  More generally,
attempting an operation on an ineligible key or value whose completion
would not result in the insertion of an ineligible element into the map may
throw an exception or it may succeed, at the option of the implementation.
Such exceptions are marked as "optional" in the specification for this
interface.

​ 一些map实现对它们可能包含的键和值有限制。例如,有些实现禁止空键和值,有些实现对键的类型有限制。试图插入不符合条件的键或值会引发未检查异常,通常NullPointerException或ClassCastException。试图查询不符合条件的键或值的存在可能会引发异常,或者只返回false;有些实现将显示前一种行为,有些实现将显示后一种行为。更一般地说,尝试对不符合条件的键或值执行操作,如果该键或值的完成不会导致将不符合条件的元素插入到映射中,则可能会引发异常,也可能会成功,这取决于实现的选项。在这个接口的规范中,这些异常被标记为“可选”。

Many methods in Collections Framework interfaces are defined in terms of the
{@link Object#equals(Object) equals} method. For example, the specification for
the {@link #containsKey(Object) containsKey(Object key)} method says:
"returns true if and only if this map contains a mapping for a key k such that
(key==null ? k==null : key.equals(k))." This specification should not be construed 
to imply that invoking Map.containsKey with a non-null argument key will cause 
key.equals(k) to be invoked for any key k. Implementations are free to implement
optimizations whereby the equals invocation is avoided, for example, by first 
comparing the hash codes of the two keys. (The {@link Object#hashCode()} specification 
guarantees that two objects with unequal hash codes cannot be equal.) More generally, 
implementations of the various Collections Framework interfaces are free to take 
advantage of the specified behavior of underlying {@link Object} methods wherever
the implementor deems it appropriate.

​ 集合框架接口中的许多方法都是用{@link Object#equals(Object) equals}方法定义的。例如,{@link #containsKey(Object) containsKey(Object key)方法的规范说:“当且仅当此映射包含键k的映射,使得(key==null ? k==null : key.equals(k))。”

​ 这个规范应该而不是被解释为调用Map。containsKey带有一个非空参数key将导致key.equals(k)被调用,用于任何k。实现可以自由地实现优化,从而避免 = 调用,例如,首先比较两个键的哈希码。({@link Object#hashCode()}规范保证哈希码不相等的两个对象不能相等。)

​ 更一般地说,各种集合框架接口的实现可以在实现者认为合适的地方自由地利用底层{@link Object}方法的指定行为。

 <p>Some map operations which perform recursive traversal of the map may fail
 with an exception for self-referential instances where the map directly or
 indirectly contains itself. This includes the {@code clone()},
 {@code equals()}, {@code hashCode()} and {@code toString()} methods.
 Implementations may optionally handle the self-referential scenario, however
 most current implementations do not do so.

​ 一些映射操作执行映射的递归遍历,可能会失败,除非映射直接或间接包含自身的自引用实例例外。这包括{@code clone()}、{@code equals()}、{@code hashCode()}{@code toString()}方法。实现可以选择性地处理自引用场景,但是大多数当前实现不这样做。

3.方法总览

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tJYx3rSe-1587823247268)(./00-java/image-20190906220641954.png)]

4.size方法

Returns the number of key-value mappings in this map.  If the
map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
<tt>Integer.MAX_VALUE</tt>.

返回此map中key-value 的数目。如果map包含的元素多于Integer.MAX_VALUE个,那么也只会返回Integer.MAX_VALUE

4.isEmpty

判断是否为空。

5.containsKey

Returns <tt>true</tt> if this map contains a mapping for the specified
key.  More formally, returns <tt>true</tt> if and only if
this map contains a mapping for a key <tt>k</tt> such that
<tt>(key==null ? k==null : key.equals(k))</tt>.  (There can be
at most one such mapping.)

​ 如果此映射包含指定键的映射,则返回true。更正式地说,当且仅当此映射包含键k的映射(key==null ?k == null: key.equals (k))。(最多可以有一个这样的映射。)

6.containsValue

Returns <tt>true</tt> if this map maps one or more keys to the
specified value.  More formally, returns <tt>true</tt> if and only if
this map contains at least one mapping to a value <tt>v</tt> such that
<tt>(value==null ? v==null : value.equals(v))</tt>.  This operation
will probably require time linear in the map size for most
implementations of the <tt>Map</tt> interface.

​ 如果此映射将一个或多个键映射到指定值,则返回true。更正式地说,当且仅当此映射包含至少一个到值v的映射(value==null ?v = = null: value.equals (v))。对于map接口的大多数实现,此操作可能需要映射大小的时间线性关系。

7.get


    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>If this map permits null values, then a return value of
     * {@code null} does not <i>necessarily</i> indicate that the map
     * contains no mapping for the key; it's also possible that the map
     * explicitly maps the key to {@code null}.  The {@link #containsKey
     * containsKey} operation may be used to distinguish these two cases.
     *
     * @param key the key whose associated value is to be returned
     * @return the value to which the specified key is mapped, or
     *         {@code null} if this map contains no mapping for the key
     * @throws ClassCastException if the key is of an inappropriate type for
     *         this map
     * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified key is null and this map
     *         does not permit null keys
     * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     */
    V get(Object key);

返回指定键映射到的值,如果此映射不包含键的映射,则返回{@code null}

更正式地说,如果这个映射包含从键{@code k}到值{@code v}的映射,使得{@code (key==null ?k==null: key.equals(k))},则该方法返回{@code v};否则返回{@code null}。(最多可以有一个这样的映射。)

如果此映射允许空值,则返回值{@code null}不一定表示该映射不包含键的映射;也有可能映射显式地将键映射到{@code null}{@link #containsKey containsKey}操作可用于区分这两种情况。

8.put

	/**
     * Associates the specified value with the specified key in this map
     * (optional operation).  If the map previously contained a mapping for
     * the key, the old value is replaced by the specified value.  (A map
     * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
     * if {@link #containsKey(Object) m.containsKey(k)} would return
     * <tt>true</tt>.)
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>,
     *         if the implementation supports <tt>null</tt> values.)
     * @throws UnsupportedOperationException if the <tt>put</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     * @throws NullPointerException if the specified key or value is null
     *         and this map does not permit null keys or values
     * @throws IllegalArgumentException if some property of the specified key
     *         or value prevents it from being stored in this map
     */
    V put(K key, V value);

​ 将指定值与此映射中的指定键关联(可选操作)。如果映射以前包含键的映射,则用指定的值替换旧值。(当且仅当{@link #containsKey(Object) m.containsKey(k)}返回true时,映射m才包含键k的映射。)

9.remove

 /**
     * Removes the mapping for a key from this map if it is present
     * (optional operation).   More formally, if this map contains a mapping
     * from key <tt>k</tt> to value <tt>v</tt> such that
     * <code>(key==null ?  k==null : key.equals(k))</code>, that mapping
     * is removed.  (The map can contain at most one such mapping.)
     *
     * <p>Returns the value to which this map previously associated the key,
     * or <tt>null</tt> if the map contained no mapping for the key.
     *
     * <p>If this map permits null values, then a return value of
     * <tt>null</tt> does not <i>necessarily</i> indicate that the map
     * contained no mapping for the key; it's also possible that the map
     * explicitly mapped the key to <tt>null</tt>.
     *
     * <p>The map will not contain a mapping for the specified key once the
     * call returns.
     *
     * @param key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     * @throws UnsupportedOperationException if the <tt>remove</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the key is of an inappropriate type for
     *         this map
     * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified key is null and this
     *         map does not permit null keys
     * (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     */
    V remove(Object key);

​ 如果键存在,则从该映射中删除键的映射(可选操作)。更正式地说,如果这个映射包含从键k到值v的映射,使得(key==null ?k==null: key.equals(k)),该映射被删除。(该映射最多可以包含一个这样的映射。)

返回此映射以前与键关联的值,如果映射不包含键的映射,则返回null。

如果该映射允许null值,则返回null值并不一定表示该映射不包含键的映射;也有可能映射显式地将键映射为null。

一旦调用返回,映射将不包含指定键的映射。

10.clear

	/**
     * Removes all of the mappings from this map (optional operation).
     * The map will be empty after this call returns.
     *
     * @throws UnsupportedOperationException if the <tt>clear</tt> operation
     *         is not supported by this map
     */
    void clear();

从该映射中删除所有映射(可选操作)。这个调用返回后映射将为空。

11.keySet

 	/**
     * Returns a {@link Set} view of the keys contained in this map.
     * 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 an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     *
     * @return a set view of the keys contained in this map
     */
    Set<K> keySet();

​ 返回此映射中包含的键的{@link Set}视图。集合由映射支持,因此对映射的更改反映在集合中,反之亦然。如果在对集合进行迭代时修改映射(除了通过迭代器自己的删除操作),迭代的结果是未定义的。集合支持元素删除,元素删除通过迭代器从映射中删除对应的映射。删除、设置、删除、删除、保留和清除操作。它不支持add或addAll操作。

12.values

 /**
     * Returns a {@link Collection} view of the values contained in this map.
     * The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  If the map is
     * modified while an iteration over the collection is in progress
     * (except through the iterator's own <tt>remove</tt> operation),
     * the results of the iteration are undefined.  The collection
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
     * support the <tt>add</tt> or <tt>addAll</tt> operations.
     *
     * @return a collection view of the values contained in this map
     */
    Collection<V> values();

​ 返回此映射中包含的值的{@link Collection}视图。集合由映射支持,因此对映射的更改将反映在集合中,反之亦然。如果在对集合进行迭代时修改映射(除了通过迭代器自己的删除操作),迭代的结果是未定义的。集合支持元素删除,元素删除通过迭代器从映射中删除对应的映射。删除收藏。拆卸、拆卸、保持和清除操作。它不支持add或addAll操作。

13.equals

  /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    boolean equals(Object o);

​ 将指定的对象与此映射进行比较以确定是否相等。如果给定对象也是一个映射,且这两个映射表示相同的映射,则返回true。更正式地说,如果m1.entrySet().equals(m2.entrySet()),则两个映射m1和m2表示相同的映射。这可以确保equals方法在Map接口的不同实现之间正常工作。

14.hashCode

	/**
     * Returns the hash code value for this map.  The hash code of a map is
     * defined to be the sum of the hash codes of each entry in the map's
     * <tt>entrySet()</tt> view.  This ensures that <tt>m1.equals(m2)</tt>
     * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
     * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
     * {@link Object#hashCode}.
     *
     * @return the hash code value for this map
     * @see Map.Entry#hashCode()
     * @see Object#equals(Object)
     * @see #equals(Object)
     */
    int hashCode();

​ 返回此映射的哈希码值。映射的哈希码被定义为映射的entrySet()视图中每个条目的哈希码之和。这确保了m1.equals(m2)意味着对于任意两个映射m1和m2, m1.hashCode()==m2.hashCode(),这是{@link Object#hashCode}的通用契约所要求的。

15.replaceAll

/**
     * 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.  Exceptions thrown by the function are
     * relayed to the caller.
     *
     * @implSpec
     * <p>The default implementation is equivalent to, for this {@code map}:
     * <pre> {@code
     * for (Map.Entry<K, V> entry : map.entrySet())
     *     entry.setValue(function.apply(entry.getKey(), entry.getValue()));
     * }</pre>
     *
     * <p>The default implementation makes no guarantees about synchronization
     * or atomicity properties of this method. Any implementation providing
     * atomicity guarantees must override this method and document its
     * concurrency properties.
     *
     * @param function the function to apply to each entry
     * @throws UnsupportedOperationException if the {@code set} operation
     * is not supported by this map's entry set iterator.
     * @throws ClassCastException if the class of a replacement value
     * prevents it from being stored in this map
     * @throws NullPointerException if the specified function is null, or the
     * specified replacement value is null, and this map does not permit null
     * values
     * @throws ClassCastException if a replacement value is of an inappropriate
     *         type for this map
     *         (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if function or a replacement value is null,
     *         and this map does not permit null keys or values
     *         (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @throws IllegalArgumentException if some property of a replacement value
     *         prevents it from being stored in this map
     *         (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
     * @throws ConcurrentModificationException if an entry is found to be
     * removed during iteration
     * @since 1.8
     */
    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Objects.requireNonNull(function);
        for (Map.Entry<K, V> entry : entrySet()) {
            K k;
            V v;
            try {
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }

            // ise thrown from function is not a cme.
            v = function.apply(k, v);

            try {
                entry.setValue(v);
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }
        }
    }

​ 将每个条目的值替换为对该条目调用给定函数的结果,直到所有条目都被处理或函数抛出异常。函数抛出的异常将传递给调用者。

@implSpec

对于这个{@code map},默认实现相当于:

for (Map.Entry<K, V> entry : map.entrySet())
    entry.setValue(function.apply(entry.getKey(), entry.getValue()));
}

默认实现不保证此方法的同步或原子性属性。任何提供原子性保证的实现都必须覆盖此方法并记录其并发性属性。

发布了1302 篇原创文章 · 获赞 470 · 访问量 165万+

猜你喜欢

转载自blog.csdn.net/qq_21383435/article/details/105757884