Importance of HashSet in Java


The HashSet use Hashing to manipulate data. Let us see an example −

Example

import java.util.*;
public class Demo{
   private final String f_str, l_str;
   public Demo(String f_str, String l_str){
      this.f_str = f_str;
      this.l_str = l_str;
   }
   public boolean equals(Object o){
      if (o instanceof Demo)
      return true;
      Demo n = (Demo)o;
      return n.f_str.equals(f_str) && n.l_str.equals(l_str);
   }
   public static void main(String[] args){
      Set<Demo> my_set = new HashSet<Demo>();
      my_set.add(new Demo("Joe", "Goldberg"));
      System.out.println("Added a new element to the set");
      System.out.println("Does the set contain a new instance of the object? ");
      System.out.println(my_set.contains(new Demo("Jo", "Gold")));
   }
}

Output

Added a new element to the set
Does the set contain a new instance of the object? 
false

The ‘Demo’ class contains a final string and a constructor. An equals function is defined that checks if an object is an instance of a specific class. It returns true if it is an instance otherwise casts the object to the class and checks using the ’equals’ function. In the main function, a new Set is created and an instance is created. This is checked for using the ‘instanceof’ operator.

Updated on: 23-Nov-2023

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements