HashMap allows a single null key and multiple null values. TreeMap does not allow null keys but can have multiple null values. HashMap allows heterogeneous elements because it does not perform sorting on keys. TreeMap allows homogeneous values as a key because of sorting.
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.
TreeMap
is an example of a SortedMap
, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.
HashMap
on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap
, you can't be sure what order they will be in.
HashMap
will be more efficient in general, so use it whenever you don't care about the order of the keys.
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.
To sum up:
Taken from: HashMap vs. TreeMap
Use HashMap
most of the times but use TreeMap
when you need the key to be sorted (when you need to iterate the keys).
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.
You almost always use HashMap
, you should only use TreeMap
if you need your keys to be in a specific order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With