Using a HashSet in Java

A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object.

For more information on hashing, check out the HashMap category.

Things to remember:
– A HashSet is not synchronized, so not thread-safe.
– Its elements are not ordered
– Add an element to the HashSet with the method add(Object o)
– Remove an element with the method remove(Object o)
– Remove all elements with the method clear()
– Get the number of elements with the method size()

Here’s an example:

import java.util.*;
import java.io.*;
    
public class Main 
{
   public static void main(String []args) throws Exception {
      String[] keywords = { "abstract", "boolean", "break", "byte", "case", "cast",
                            "catch", "char", "class", "const", "continue", "default",
                            "do", "double", "else", "extends", "final", "finally",
                            "float", "for", "future", "generic", "goto", "if",
                            "implements", "import", "inner", "instanceof", "int",
                            "interface", "long", "native", "new", "null", "operator",
                            "outer", "package", "private", "protected", "public",
                            "rest", "return", "short", "static", "super", "switch",
                            "synchronized", "this", "throw", "throws", "transient",
                            "try", "var", "void", "volatile" };
 
      // convert this array to a Collection and create a HashSet
      HashSet hs = new HashSet(Arrays.asList(keywords));
 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      
      String line;
      System.out.print("Enter keyword ('exit' to exit): ");
      line = br.readLine();
      while (!line.equals("exit")) {
         if (hs.contains(line)) {
            System.out.println("t" + line + " is a Java keyword!");
         }
         else {
            System.out.println("t" + line + " is not a Java keyword!");
         }
         System.out.print("Enter keyword ('exit' to exit): ");
         line = br.readLine();
      }
   }
}

sample output:

C:>java Main
Enter keyword ('exit' to exit): public
        public is a Java keyword!
Enter keyword ('exit' to exit): jefke
        jefke is not a Java keyword!
Enter keyword ('exit' to exit): instanceof
        instanceof is a Java keyword!
Enter keyword ('exit' to exit): coke
        coke is not a Java keyword!
Enter keyword ('exit' to exit): esus
        esus is not a Java keyword!
Enter keyword ('exit' to exit): package
        package is a Java keyword!
Enter keyword ('exit' to exit): exit