Importance of HashSet in Java

JavaObject Oriented ProgrammingProgramming

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

Example

 Live Demo

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.

raja
Published on 04-Jul-2020 11:41:03
Advertisements