How to use different Maps in Java

Sourin Sutradhar
Programming Notes
Published in
1 min readNov 9, 2016

--

Here I will be talking about HashMap, HashTable and TreeMap, all of which implement the Map interface

To start with, HashMap and HashTable both implements Map interface and looks similar, however there are significant differences between their applications. HashMap allows null key and values whereas HashTable doesn’t allow null key and values. HashTable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, HashTable is suitable for multi-threaded environment. LinkedHashMap was introduced in Java 1.4 as a subclass of HashMap, so incase you want iteration order, you can easily switch from HashMap to LinkedHashMap but that is not the case with HashTable whose iteration order is unpredictable. HashMap provides Set of keys to iterate and hence it’s fail-fast but HashTable provides Enumeration of keys that doesn’t support this feature. HashTable is considered to be legacy class and if you are looking for modifications of Map while iterating, you should use ConcurrentHashMap.

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

--

--