Map集合:
Map接口
Map与List、Set接口不同,它是由一系列键值对组成的集合,提供了key到Value的映射。同时它也没有继承Collection。在Map中它保证了key与value之间的一一对应关系。也就是说一个key对应一个value,所以它不能存在相同的key值,当然value值可以相同。
1.HashMap
以哈希表数据结构实现,查找对象时通过哈希函数计算其位置,它是为快速查询而设计的,其内部定义了一个hash表数组(Entry[] table),元素会通过哈希转换函数将元素的哈希地址转换成数组中存放的索引,如果有冲突,则使用散列链表的形式将所有相同哈希地址的元素串起来,可能通过查看HashMap.Entry的源码它是一个单链表结构。
2.LinkedHashMap
LinkedHashMap是HashMap的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用LinkedHashMap。
LinkedHashMap是Map接口的哈希表和链接列表实现,具有可预知的迭代顺序。此实现提供所有可选的映射操作,并允许使用null值和null键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。
LinkedHashMap实现与HashMap的不同之处在于,后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可以是插入顺序或者是访问顺序。
根据链表中元素的顺序可以分为:按插入顺序的链表,和按访问顺序(调用get方法)的链表。默认是按插入顺序排序,如果指定按访问顺序排序,那么调用get方法后,会将这次访问的元素移至链表尾部,不断访问可以形成按访问顺序排序的链表。
注意,此实现不是同步的。如果多个线程同时访问链接的哈希映射,而其中至少一个线程从结构上修改了该映射,则它必须保持外部同步。
由于LinkedHashMap需要维护元素的插入顺序,因此性能略低于HashMap的性能,但在迭代访问Map里的全部元素时将有很好的性能,因为它以链表来维护内部顺序。
3.TreeMap
TreeMap 是一个有序的key-value集合,非同步,基于红黑树(Red-Black tree)实现,每一个key-value节点作为红黑树的一个节点。TreeMap存储时会进行排序的,会根据key来对key-value键值对进行排序,其中排序方式也是分为两种,一种是自然排序,一种是定制排序,具体取决于使用的构造方法。
自然排序:TreeMap中所有的key必须实现Comparable接口,并且所有的key都应该是同一个类的对象,否则会报ClassCastException异常。
定制排序:定义TreeMap时,创建一个comparator对象,该对象对所有的treeMap中所有的key值进行排序,采用定制排序的时候不需要TreeMap中所有的key必须实现Comparable接口。
TreeMap判断两个元素相等的标准:两个key通过compareTo()方法返回0,则认为这两个key相等。
如果使用自定义的类来作为TreeMap中的key值,且想让TreeMap能够良好的工作,则必须重写自定义类中的equals()方法,TreeMap中判断相等的标准是:两个key通过equals()方法返回为true,并且通过compareTo()方法比较应该返回为0。
以下基于JDK1.9
public interface Map<K,V>
This interface takes the place of the Dictionary
class, which was a totally abstract class rather than an interface.
一个将键映射到值的对象。地图不能包含重复的键;每个键最多只能映射到一个值。
这个接口取代了Dictionary类,它是一个完全抽象的类,而不是一个接口。
The Map
interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The orderof 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 TreeMap
class, make specific guarantees as to their order; others, like the HashMap
class, do not.
Map接口提供三个托收视图,允许将Map的内容视为一组键、值集合或键值映射集。映射的顺序是指映射集合视图上的迭代器返回它们的元素的顺序。一些映射实现,如TreeMap类,对它们的顺序做出具体的保证;其他的,如HashMap类,则没有。
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 equals
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 equals
and hashCode
methods are no longer well defined on such a map.
注意:如果可变对象被用作map键,必须执行非常小心的操作。如果一个对象的值发生了改变,而对象是map中的键,那么就不会指定映射的行为。这条禁令的一个特例是,地图不允许将自己作为一个密钥。虽然可以允许map将自身作为一个值来包含,但是要特别注意:在这样的映射中,equals和hashCode方法不再很好地定义。
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 Map
, 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实现类都应该提供两个“标准”构造器:一个void(无参数)构造器,它创建一个空的映射,一个构造函数带有一个类型映射的单一参数,它创建了一个新的映射,它的键值映射和它的参数一样。实际上,后者的构造函数允许用户复制任何映射,生成所需类的等效映射。没有办法强制执行这个建议(因为接口不能包含构造函数),但是JDK中的所有通用映射实现都遵从了。
The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throwUnsupportedOperationException
if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException
if the invocation would have no effect on the map. For example, invoking the 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.
此接口中包含的“破坏性”方法,即修改地图的方法操作,指定throwUnsupportedOperationException如果这张地图不支持的操作。如果是这样的话,这些方法可能,但不需要,抛出UnsupportedOperationException如果调用方式在地图上没有影响。例如,在不可修改的映射上调用putAll(Map)方法,但不需要,如果映射为“叠加”的映射为空,则抛出异常。
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 NullPointerException
or ClassCastException
. 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.
有些映射实现对它们可能包含的键和值有限制。例如,有些实现禁止空键和值,有些实现对键的类型有限制。试图插入一个不合格的键或值抛出未检查的异常,通常是NullPointerException或ClassCastException。试图查询一个不合格的键或值的存在可能会抛出异常,或者它可能只是返回false;一些实现将展示前者的行为,而有些实现将展示后者。更一般的情况是,尝试在不符合条件的键或值上执行操作,如果没有将不符合条件的元素插入到map中,则可能会抛出异常,或者在实现的选项中可能成功。在该接口的规范中,这些异常被标记为“可选”。
Many methods in Collections Framework interfaces are defined in terms of the equals
method. For example, the specification for the 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 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 Object
methods wherever the implementor deems it appropriate.
集合框架接口中的许多方法都是用equals方法定义的。例如,容器键(Object key)方法的规范说:“如果且仅当这个映射包含一个键k的映射时返回true(key==null吗?k = = null:key.equals(k))。”该规范不应被解释为暗示调用Map。带有非空参数键的容器键将会引起键.equals(k)被调用,因为任何关键k实现都可以自由地实现优化,从而避免相等的调用,例如,首先比较两个键的散列码。(object.hashcode()规范保证了不相等的哈希码的两个对象不能相等。)更广泛地说,各种集合框架接口的实现可以自由地利用底层对象方法的指定行为,无论实现者认为它是合适的。
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 clone()
, equals()
, hashCode()
and toString()
methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.