Java Advanced Maps

一提到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 to Map, 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...

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • 今天孩子學校因為流感放假兩天,吃過早飯,孩子就在家里待不住了,要找人玩,要出門去,被我阻止了。過了一會兒,我正整理...
    清文雅書閱讀 360評論 2 2
  • ?????????????????????????????????????????????????????????...
    吐蕃的男孩閱讀 174評論 0 0
  • 2018年2月4日 晴 今天淑涵表現(xiàn)挺棒的,今早我起床的時候她已經(jīng)早起來...
    老大淑涵閱讀 179評論 0 1

友情鏈接更多精彩內(nèi)容