We have read about the HashMap and TreeMap in java in recent posts. Both implement the Map interface and provide implementation to store the object based on key and value. Both are used to store the collection of objects based on key-value pairs. But both have some differences and similarities. In this post, we will see the difference between HashMap and TreeMap. Let’s find the HashMap vs TreeMap:
1. HashMap implements the Map interface and uses the hashing to save and retrieve data. But TreeMap implements the SortedMap interface and internally uses the LinkedList structure. Since Java 8 it uses a Self-Balancing Binary Search Tree.
2. HashMap stores the object based on a unique key but it doesn’t maintain the order of objects. It does not guarantee that the order will remain constant over time.
TreeMap also stores the object like HashMap but it maintains the order of the object. The objects of TreeMap are sorted according to the natural ordering of its keys, or we can store them by a Comparator provided at map creation time.
3. HashMap can store only one null key and multiple null values.
But TreeMap can’t contain any null key and null value. If we add any null key or value. It throws NullPointerException.
4. HashMap has the complexity O(1) in case of it get, put, and remove operations.
While TreeMap has the complexity O(log(n)) in case of it get, put and remove operations.
5. HashMap uses the equals() method of the Object class to compare the objects of HashMap. TreeMap uses the compareTo() method to compare the objects of TreeMap.
6. HashMap is much faster than TreeMap.