Friday, July 26, 2019

HashMap Vs TreeMap In Java

HsahMap:
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>
Direct Known Subclasses:
LinkedHashMap, PrinterStateReasons
TreeMap:
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable

All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>
public interface NavigableMap<K,V>
extends SortedMap<K,V>
Similarities between HsahMap and Synchronized
  • HashMap and TreeMap both classes belong to java.util package and both are the members of the Java Collections Framework.
  • HashMap and TreeMap both store key value pair as object.
  • Iterator's returned by HashMap and TreeMap both are fail-fast.
  • HashMap and TreeMap both uses shallow copy method to create clone of their objects.
  • HashMap and TreeMap both are not thread safe means unsynchronized. 
Although we can externally create both synchronized as mention below using Collections method.
HashMap :  Map m = Collections.synchronizedMap(new HashMap (...));
TreeMap :  Map m = Collections.synchronizedSortedMap(new TreeMap (...));
Difference between HsahMap and Synchronized
HsahMap TreeMap
HsahMap is hash table based implementation of the Map interface. TreeMap use Red-Black tree based NavigableMap implementation which is a self-balancing Binary Search Tree.
HashMap allows a only single null key and multiple null values. TreeMap does not allow any null keys but can have multiple null values.
HashMap is faster than TreeMap, it provides constant-time performance that is O(1) for the basic operations like get() and put(). TreeMap is slow compared to HashMap because it provides the performance of O(log(n)) for most operations like add(), remove() and contains().
HsahMap uses equals() method of the Object class to compare keys. The equals() method of Map class to overrides its values. HsahMap uses the compareTo() method to compare keys.
HashMap has only basic functions like get(), put(), KeySet(), etc. TreeMap has more functions like: tailMap(), firstKey(), lastKey(), pollFirstEntry(), pollLastEntry().
HashMap does not preserve insertion order. HashMap does not provide any guarantee that the element inserted. The elements are sorted in natural order (ascending).


No comments:

Post a Comment