Difference between HashMap and HashSet in Java.

Java 8Object Oriented ProgrammingProgramming

HashMap and HashSet both are one of the most important classes of Java Collection framework.

Following are the important differences between HashMap and HashSet.

Sr. No.KeyHashMapHashSet
1ImplementationHashmap is the implementation of Map interface.Hashset on other hand is the implementation of set interface.
2Internal implementationHashmap internally do not implements hashset or any set for its implementation.Hashset internally uses Hashmap for its implementation.
3Storage of elementsHashMap Stores elements in form of key-value pair i.e each element has its corresponding key which is required for its retrieval during iteration.HashSet stores only objects no such key value pairs maintained.
4Method to add elementPut method of hash map is used to add element in hashmap.On other hand add method of hashset is used to add element in hashset.
5Index performanceHashmap due to its unique key is faster in retrieval of element during its iteration.HashSet is completely based on object so compared to hashmap is slower.
6Null AllowedSingle null key and any number of null value can be inserted in hashmap without any restriction.On other hand Hashset allows only one null value in its collection,after which no null value is allowed to be added.

Example of Hashmap vs Hashset

JavaTester.java

 Live Demo

import java.util.HashSet;
public class JavaTester {
   public static void main(String[] args){
      HashSet<String> hs = new HashSet<String>();
      hs.add("John");
      hs.add("Smith");
      hs.add("Peter");
      System.out.println("Before adding duplicate values \n\n" + hs);
      hs.add("John");
      hs.add("Smith");
      System.out.println("\nAfter adding duplicate values \n\n" + hs);
      hs.add(null);
      hs.add(null);
      System.out.println("\nAfter adding null values \n\n" + hs);
   }
}

Output

Before adding duplicate values
[John, Smith, Peter]
After adding duplicate values
[John, Smith, Peter]
After adding null values
[null, John, Smith, Peter]

Example

JavaTester.java

 Live Demo

import java.util.HashMap;
public class JavaTester {
   public static void main(String[] args){
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      hm.put(12, "John");
      hm.put(2, "Smith");
      hm.put(7, "Peter");
      System.out.println("\nHashMap object output :\n\n" + hm);
      hm.put(12, "Smith");
      System.out.println("\nAfter inserting duplicate key :\n\n" + hm);
   }
}

Output

HashMap object output :
{2=Smith, 7=Peter, 12=John}
After inserting duplicate key :
{2=Smith, 7=Peter, 12=John}
raja
Published on 18-Sep-2019 12:17:12
Advertisements