/** * An object that maps keys to values. A map cannot contain duplicate keys; * each key can map to at most one value. * * <p>This interface takes the place of the <tt>Dictionary</tt> class, which * was a totally abstract class rather than an interface. * * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which * allow a map's contents to be viewed as a set of keys, collection of values, * or set of key-value mappings. The <i>order</i> of a map is defined as * the order in which the iterators on the map's collection views return their * elements. Some map implementations, like the <tt>TreeMap</tt> class, make * specific guarantees as to their order; others, like the <tt>HashMap</tt> * class, do not. * * <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. * * <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. * * <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. * * <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. * * <p>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 <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>." This specification should * <i>not</i> be construed to imply that invoking <tt>Map.containsKey</tt> * with a non-null argument <tt>key</tt> will cause <tt>key.equals(k)</tt> to * be invoked for any key <tt>k</tt>. Implementations are free to * implement optimizations whereby the <tt>equals</tt> 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. * * <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. * * <p>This interface 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 Josh Bloch * @see HashMap * @see TreeMap * @see Hashtable * @see SortedMap * @see Collection * @see Set * @since 1.2 */ public interface Map<K,V>
Map是一個接口,一個map不能包含重復的key,每個key只能映射唯一一個value。
Map接口是用來取代Dictionary抽象類的。
Map接口提供三個集合視圖,1.key的集合 2.value的集合 3.key-value的集合。map內元素的順序取決於Iterator的具體實現,獲取集合視圖其實是獲取一個迭代器,實現對遍歷元素細節的隱藏。TreeMap類能保證遍歷元素的順序,而HashMap就無法保證遍歷元素的順序。
注意:當使用一個可變對象作為key的時候要小心,map是根據hashCode和equals方法決定存放的位置的。一個特殊的案例是不允許一個map將自己作為一個key,但允許將自己作為一value。
所有多種用途的map實現類應該提供兩個“標准”構造器,一個無參構造器用來創建一個空map,一個只有一個參數,參數類型是map的構造器,用來創建一個新的和傳入參數有一樣key-value映射的map。實際上,后者允許復制任何一個map,這僅僅是一個建議,並沒有強制要求,因為接口是無法包含構造器的,不過這個建議在JDK被遵守。
如果一個方法的操作是不被支持的,這個方法指定拋出UnsupportedOperationException異常。如果這個操作對mao是沒有影響的,那么也可以不拋出UnsupportedOperationException異常。例如,在一個不能被修改的map調用putAll(Map)方法,如果該map的映射是空的,就不要求拋出UnsupportedOperationException異常。
Map接口是Java Collections Framework的一員。
Map里面的方法:
int size();//返回map中key-value映射的數量 boolean isEmpty();//如果map中沒有key-value映射返回true
//如果map不含key映射,返回false,當key的類型不符合,拋出ClassCastException,當key是
//null且該map不支持key的值是null時,拋出NullPointerException boolean containsKey(Object key);
//如果map含有一個以上的key映射的參數value,返回true,異常拋出的情況和containKey一樣 boolean containsValue(Object value);
//根據key得到對應的value,如果沒有對應的映射,返回null,如果map允許value為null,返回
//null可能是有一對key-null的映射或沒有對應的映射
V get(Object key);
//往map放入一對key-value映射 V put(K key, V value);
//根據key刪除對應映射 V remove(Object key);
//復制一份與參數一樣的map void putAll(Map<? extends K, ? extends V> m);
//清空map中所有的映射 void clear();
//返回map中所有key的集合 Set<K> keySet();
//返回map中所有value的集合 Collection<V> values();
//返回key-value的集合 Set<Map.Entry<K, V>> entrySet();
//比較調用者與參數是否相等 boolean equals(Object o);
//計算map的hash code int hashCode(); //還有其他default方法...,都是jdk1.8發布的
Map接口里有一個內部接口Entry<K,V>,其實它就是Map存放key-value映射的數據結構
interface Entry<K,V> {
//返回對應的key K getKey();
//返回對應的value V getValue();
//設置用新value替換舊value,返回值是舊value V setValue(V value);
//如果兩個entry的映射一樣,返回true boolean equals(Object o);
//計算entry的hash code int hashCode();
//下面的靜態方法是JDK1.8才發布的
//返回一個比較器,比較的規則是key的自然大小 public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey());//這里用的是lambda表達式 }
//返回一個比較器,比較規則是value的自然大小 public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getValue().compareTo(c2.getValue()); }
//返回一個比較器,比較規則用參數傳入,比較的是key public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); }
//返回一個比較器,比較規則用參數傳入,比較的是value public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); } }