Computer >> Computer tutorials >  >> Programming >> Java

Difference Between HashMap and TreeMap in Java


In this post, we will understand the difference between hashmap and treemap, associated with Java.

HashMap

  • It is a hash table in Java.

  • It is based on the implementation of ‘map’ interface.

  • It implements ‘Map, ‘Cloneable’, and ‘Serializable’ interfaces.

  • It allows a single null key.

  • It also allows multiple null values.

  • It is quicker in comparison to Treemap.

  • This is because it provides constant-time performances, i.e O(1) for operations like ‘get’ and ‘put’.

  • It doesn’t perform sorting on keys.

  • Hence it allows heterogeneous elements in the HashMap.

  • It doesn’t maintain the order of elements.

  • It can be used when a key-value pair in a sorted order is NOT needed.

  • It uses the ‘equals’ method of Object class to compare keys.

  • The ‘equals’ method of Map class overrides it.

  • It only contains basic methods like ‘KeySet’, ‘get’, ‘put’.

TreeMap

  • It is a tree structure used in Java.

  • It is based on the implementation of ‘map’ interface.

  • It implements ‘NavigableMap’, ‘Cloneable’, and the ‘Serializable’ interface.

  • It doesn’t allow null keys.

  • It allows multiple null values.

  • It allows homogeneous values as a key since it is sorted.

  • It is slow in comparison to HashMap since it provides complexity of O(log(n)) for most of the operations such as add(), remove() and contains().

  • It uses a Red-Black tree internally.

  • Red black tree is a self-balancing Binary Search Tree.

  • The compareTo() method is used in order to compare keys.

  • It has many functionalities such as tailMap(), firstKey(), lastKey(), pollFirstEntry(), pollLastEntry().

  • The elements are sorted in ascending order, also known as natural order.

  • It is used when the requirement is a key-value pair in a sorted order.