I started learning Java. When would I use a HashMap over a TreeMap?
This question is related to
java
HashMap
is implemented by Hash Table while TreeMap
is implemented by Red-Black tree
. The main difference between HashMap
and TreeMap
actually reflect the main difference between a Hash
and a Binary Tree
, that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.
Take a look at following diagram.
HashMap
is used for fast lookup, whereas TreeMap
is used for sorted iterations over the map.
To sum up:
Taken from: HashMap vs. TreeMap
You almost always use HashMap
, you should only use TreeMap
if you need your keys to be in a specific order.
Use HashMap
most of the times but use TreeMap
when you need the key to be sorted (when you need to iterate the keys).
Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.
I'll talk about the HashMap and TreeMap implementation in Java:
HashMap -- implement basic map interface
Map m = Collections.synchronizedMap(new HashMap(...));
TreeMap -- implement navigable map interface
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
To sum, the biggest difference between HashMap and TreeMap is that TreeMap implements NavigableMap<K,V>
, which provide the feature of ordered iteration. Besides, both HashMap and TreeMap are members of Java Collection framework. You can investigate the source code of Java to know more about their implementations.
Source: Stackoverflow.com