一提到Map,我們最常想到的是HashMap。在實際coding過程中,陸續(xù)遇到其他的一些map implementation,想在此分享:
LinkedHashMap
IdentityHashMap: Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.
Note that this implementation is not synchronized.
簡言之,和HashMap比較來說,LinkedHashMap能夠保證entry的順序。
IdentityHashMap
IdentityHashMap: This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)
Note that this implementation is not synchronized.
簡言之,對于key和value,HashMap用equals比較大小,而IdentityHashMap用 == 比較大小,比HashMap更快。
Multimap
Multimap: A collection that maps keys to values, similar toMap, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:
- a → 1, 2
- b → 3
... or as a single "flattened" collection of key-value pairs:- a → 1
- a → 2
- b → 3
每個key可以對應多個values。
Tips
以引用里的key, values為例:
-
myMultimap.values()collection is [1, 2, 3], not [[1, 2], [3]]. -
myMultimap.size()is 3, not 2.
Map.Entry<K, V>
Map.Entry<K, V>是一個interface。它的implementation包括:AbstractMap.SimpleEntry<K,V>
AbstractMap.SimpleImmutableEntry<K,V>
正因為Map.Entry<K, V>是interface,我們不能instantiate它(比如new)。
To be continue...