HashMap vs HashSet

Difference between HashSet and HashMap

HashMap HashSet
1)HashMap class implements the Map interface. HashSet class implements the Set interface.
2) HashMap is not part of collection inteface.  HashSet is part of Collection interface.
3) HashMap are use to store key & value pairs. HashSetare use to store only value or element.
4) HashMap does not allow duplicate keys however it allows to have duplicate values. HashSet does not allow duplicate elements that means you can not store duplicate values in HashSet.
5) HashMap allow single null key and any number of null values. HashSet allows  single null value.
6) we use put() method to insert key and value into HashMap . we use add() method to put elements into HashSet Set .

 

Similarities between HashSet and HashMap

  1. Both HashMap and HashSet are hash based collection in Java.
  2.  Both HashMap and HashSet are not synchronized which means they are not suitable for thread-safe operations unitl unless synchronized explicitly. This is how you can synchronize them explicitly:
    HashSet:

          Set s = Collections.synchronizedSet(new HashSet(…));

           HashMap:

           Map m = Collections.synchronizedMap(new HashMap(…));

  1. Both HashMap and HashSet does not guarantee that the order will remain constant over time.
  2.  If you look at the source code of HashSet then you may find that it is backed up by a HashMap. So basically it internally uses a HashMap for all of its operations.
  3. Both HashMap and HashSet provided constant time performance for basic operations like put(), get() etc.
    Both HashSet and HashMap allows null values.

HashSet example

import java.util.HashSet;
class HashSetDemo{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();
 
     //add elements to HashSet
     hset.add("A");
     hset.add("B");
     hset.add("C");
     hset.add("D");
 
     // Displaying HashSet elements
  
     for(String temp : hset){
        System.out.println(temp);
     }
  }
}

Output:


A
B
C
D

HashMap example

import java.util.HashMap;
class HashMapDemo{ 
  public static void main(String[] args) {
     // Create a HashMap
     HashMap<Integer, String> hmap = new HashMap<Integer, String>();
 
     //add elements to HashMap
     hmap.put(1, "A");
     hmap.put(2, "B");
     hmap.put(3, "C");
     hmap.put(4, "D");
 
     // Displaying HashMap elements
     System.out.println(hmap);
  }
}

Output:

 {1=A, 2=B, 3=C, 4=D}

Leave a comment