当前位置: 动力学知识库 > 问答 > 编程问答 >

java: maps zoo, what to choose

问题描述:

I'm pretty new to the Java World (since I'm writing primary in C/C++). I'm using maps in my apps.

Since java.util.Map is abstract I need to instantiate it's implementation. Usually I use HashMap like:

Map<String, MyClass> x = new HashMap<>();

But in java docs I found many other implementations, like TreeMap, LinkedHashMap, HashTable, etc. I want to know if I can continue blindly using of the HashMap or there are any important differences between those Map implementations.

The brief list of points-to-know will be ok.

Thanks.

网友答案:
  • Never bother with Hashtable, it's a relic from Java 1.0;
  • HashMap is the universal default due to O(1) lookup and reliance only on equals and hashCode, guaranteed to be implemented for all Java objects;
  • TreeMap gives you sorted iteration over the map entries (plus a lot more—see NavigableMap), but requires a comparison strategy and has slower insertion and lookup – O(logN) – than HashMap;
  • LinkedHashMap preserves insertion/access order when iterating over the entries.

SortedMap implementations offer some great features, like headMap and tailMap. NavigableMap implementations offer even more features with terrific performance for operations that assume sorted keys.

Further out there are java.util.concurrent map implementations, like ConcurrentHashMap, which offer great concurrent performance and atomic get/put operations.

网友答案:
  • HashMap use it almost all the time. Note that your object need have proper implementation of equals and hashCode methods. Does not save insertion order.
  • HashTable don't use it never.
  • LinkedHashMap the same as HashMap but saves insertion order. Large overhead.
  • TreeMap support natural ordering. But insertion works in O(logn).
网友答案:
  • Hashtable is the thread safe version of HashMap, you shouldn't use it anymore. instead you should use ConcurrentHashMap which is a new implementation of a thread safe map
  • TreeMap is mostly use when you want to sort your keys, it implements the SortedMap interface. The put/get performance is O(logn).
  • ConcurrentSkipListMap is used if you need a thread safe SortedMap
  • LinkedHashMap is used when you want to iterate on keys in the insertion order

I mostly use HashMap or ConcurrentHashMap if I need it to be thread safe

网友答案:

There of course are important differences between each of these maps. It depends purely on what you are trying to do. If you recall a HashMap becomes pretty useless (see inefficient) when you have a poor hashing function in place. The LinkedHashMap is a HashMap that is backed by a doubly linked list, so you can iterate over it. You would eat the overhead that is associated with a linked list of course. TreeMap keeps elements in order, so you will eat that overhead. HashTable is a synchronized collection, that is generally avoided.

分享给朋友:
您可能感兴趣的文章:
随机阅读: