美文网首页
Java Advanced Maps

Java Advanced Maps

作者: YoungJadeStone | 来源:发表于2018-02-23 05:46 被阅读0次

    一提到Map,我们最常想到的是HashMap。在实际coding过程中,陆续遇到其他的一些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...

    相关文章

      网友评论

          本文标题:Java Advanced Maps

          本文链接:https://www.haomeiwen.com/subject/clytxftx.html