I'm pretty new to the Java World (since I'm writing primary in C/C++). I'm using maps in my apps.
java.util.Map is abstract I need to instantiate it's implementation. Usually I use
Map<String, MyClass> x = new HashMap<>();
But in java docs I found many other implementations, like
HashTable, etc. I want to know if I can continue blindly using of the
HashMap or there are any important differences between those
The brief list of points-to-know will be ok.
Hashtable, it's a relic from Java 1.0;
HashMapis the universal default due to O(1) lookup and reliance only on
hashCode, guaranteed to be implemented for all Java objects;
TreeMapgives 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
LinkedHashMappreserves insertion/access order when iterating over the entries.
SortedMap implementations offer some great features, like
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.
HashMapuse it almost all the time. Note that your object need have proper implementation of
hashCodemethods. Does not save insertion order.
HashTabledon't use it never.
LinkedHashMapthe same as
HashMapbut saves insertion order. Large overhead.
TreeMapsupport natural ordering. But insertion works in O(logn).
I mostly use
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.