HashMap vs HashSet vs Hashtable – HashMap, HashTable, TreeMap and LinkedHashMap with Examples

HashMap vs HashSet vs Hashtable – HashMap, HashTable, TreeMap and LinkedHashMap with Examples:
Collections:
HashMap, HashSet and Hashtable are a part of Collections. (HashSet Here)

collections

map

 

HashMap, HashSet and HashTable:

HashMap, HashSet and Hashtable usually store values in key value pair. In this article we are going to understand in detail regarding HashMap, HashSet and HashTable

HashMap HashSet Hashtable
It allows null for both key and values HashSet permits to have a single null value It does not allow null for both key and value
HashMap does not maintain any order HashSet does nto maintain any insertion order, cause insertion order is not constant overtime. But if we use LinkedHashSet it maintains an order Hashtable does not maintain insertion order
HashMap uses put method to insert into hashmap HashSet uses add method to insert into hashset HashTable uses put method to insert into hashtable
HashMap is not Synchronized, better performance HashSet is not Synchronized but can be synchronized externally HashTable is Synchronized (thread safe)

We can see there are 4 types under Map (from the diagram above)

  • HashMap
  • Hashtable
  • TreeMap
  • LinkedHashMap

HashMap:
HashMap (Key, Value) pairs. HashMap is Unsynchronized and accepts null key and value pairs. HashMap can have only one null key, However if you pass another null key with different value, the value at null key will get replaced by new value.

Hashtable:
Hashtable is similar to HashMap except, Hashtable is Synchronized and does not accept null key value pairs.

TreeMap:
TreeMap is NavigableMap implementation, It is sorted according to order of keys.

LinkedHashMap:
LinkedHashMap stores the key value pair by insertion order.

In the above example, We have used HashMap, Hashtable, TreeMap and LinkedHashMap, Now let us see the output of this code. We will be able to understand the sorting order how it gets sorted from output.

op1
op2
From the output, We can see that Hashtable orders on descending order, TreeMap sorts on natural key ordering and LinkedHashMap sortes as per insertion order.

One thought on “HashMap vs HashSet vs Hashtable – HashMap, HashTable, TreeMap and LinkedHashMap with Examples

Leave a Reply

Your email address will not be published. Required fields are marked *