Computer >> Computer tutorials >  >> Programming >> Java

The HashSet in Java


HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.

A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.

The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.

Example

Let us see an example to implement HashSet in Java −

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> hashSet = new HashSet <String>();
      hashSet.add("One");
      hashSet.add("Two");
      hashSet.add("Three");
      hashSet.add("Four");
      hashSet.add("Five");
      hashSet.add("Six");
      System.out.println("Hash set values = "+ hashSet);
   }
}

Output

Hash set values = [Five, Six, One, Four, Two, Three]

Example

Let us see another example to remove element from HashSet −

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> newset = new HashSet <String>();
      newset.add("Learning");
      newset.add("Easy");
      newset.add("Simply");
      System.out.println("Values before remove: "+newset);
      boolean isremoved = newset.remove("Easy");
      System.out.println("Return value after remove: "+isremoved);
      System.out.println("Values after remove: "+newset);
   }
}

Output

Values before remove: [Learning, Easy, Simply]
Return value after remove: true
Values after remove: [Learning, Simply]