1.

Differentiate between HashMap and TreeMap in the context of Java.

Answer»
HashMapTreeMap
The Java HashMap implementation of the MAP interface is BASED on hash tables.Java TreeMap is a Map interface implementation based on a Tree structure.
The Map, Cloneable, and Serializable interfaces are implemented by HashMap.NavigableMap, Cloneable, and Serializable interfaces are implemented by TreeMap.
Because HashMap does not order on keys, it allows for heterogeneous elements.Because of the sorting, TreeMap allows homogenous values to be USED as a key.
HashMap is quicker than TreeMap because it offers O(1) constant-time performance for basic OPERATIONS such as to get() and put().TreeMap is slower than HashMap because it performs most operations with O(log(n)) performance, such as add(), remove(), and contains().
A SINGLE null key and numerous null values are allowed in HashMap.TreeMap does not allow null keys, however multiple null values are allowed.
To compare keys, it uses the Object class's equals() method. It is overridden by the Map class's equals() function.It compares keys using the compareTo() method.
HashMap does not keep track of any sort of order.The elements are arranged in chronological sequence (ascending).
When we don't need a sorted key-value pair, we should use the HashMap. When we need a key-value pair in sorted (ascending) order, we should use the TreeMap.


Discussion

No Comment Found