Last Updated: 22 January, 2023
HashMap and TreeMap are implementations of the Map interface in Java, and both are by default synchronised classes and available in the java.util package.
There are many differences between the HashMap and TreeMap that are given below.
The HashMap class was introduced in the Java 1.2 version and is available in the java.util package. HashMap is a child class of the AbstractMap class, and it implements the Map interface as well as the Cloneable and Serializable interfaces.
HashMap is used to store the data in the form of key-value pairs, where keys must be unique and values may be duplicated. HashMap accepts only one null key and multiple null values.
Java HashMap Class Declaration
Here, K is the key Object type and V is the value Object type.
Java HashMap important features:
The TreeMap class is a child class of AbstractMap, and it implements the NavigableMap interface, which is a child interface of SortedMap. The TreeMap class was introduced in JDK 1.2 and is found in the java.util package.
The TreeMap class is used to store the data in the form of key-value pairs, and its implementation is based on red-black tree concepts.
Java TreeMap Class Declaration
Here, K is the key Object type and V is the value Object type.
Java TreeMap important features:
HashMap | TreeMap |
---|---|
HashMap is a hashtable-based implementation of the Map interface. | TreeMap is a tree-structure-based (internally, it uses a Red-Black tree) implementation of the NavigableMap interface. |
HashMap implements the Map, Cloneable, and Serializable interfaces. | TreeMap implements the NavigableMap, Cloneable, and Serializable interfaces. |
HashMap allows only one null key and multiple null values. | TreeMap does not allow null keys but can have multiple null values. |
HashMap does not maintain the insertion order of elements. | TreeMap elements are sorted in natural order (ascending). |
HashMap uses the equals() method of the Object class to compare keys. The equals() method of the Map class overrides it. | TreeMap uses the compareTo() method to compare keys. |
HashMap allows heterogeneous elements because it does not perform sorting on keys. | TreeMap allows homogeneous values as a key because of sorting. |
HashMap is much faster than TreeMap. | In comparison to HashMap, TreeMap is slower. |
HashMap contains only basic functions. | TreeMap is rich in functionality. |
The HashMap should be used when we do not require key-value pairs in sorted order. | The TreeMap should be used when we require key-value pairs in sorted (ascending) order. |
Output
Iterating Hashmap and printing Key and Value
in - India
en - England
us - United State
ca - Canada
Output
TreeMap Elements:{10=Apple, 20=Banana, 30=Mango, 40=Payaya, 50=Grapes}
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com