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.
Hashtable, it’s a relic from Java 1.0;HashMapis the universal default due to O(1) lookup and reliance only onequalsandhashCode, guaranteed to be implemented for all Java objects;TreeMapgives you sorted iteration over the map entries (plus a lot more—seeNavigableMap), but requires a comparison strategy and has slower insertion and lookup – O(logN) – thanHashMap;LinkedHashMappreserves insertion/access order when iterating over the entries.SortedMapimplementations offer some great features, likeheadMapandtailMap.NavigableMapimplementations offer even more features with terrific performance for operations that assume sorted keys.Further out there are
java.util.concurrentmap implementations, likeConcurrentHashMap, which offer great concurrent performance and atomic get/put operations.