Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of HashSet.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of HashSet.

Objective

Write a Java program to demonstrate uniqueness and hashing using a HashSet.

Algorithm / Approach

  1. Create a HashSet.
  2. Add several programming languages to the set.
  3. Attempt to add a duplicate value (e.g., "c" twice).
  4. Print the set to observe that the duplicate was ignored and the insertion order was NOT preserved.
  5. Add and remove elements using the standard Collection methods.
Test.java
import java.util.*;
class Test {
 public static void main(String[] a)
 {
  HashSet lang = new HashSet();
  lang.add("java");
  lang.add("c");
  lang.add("J2ee");
  lang.add("python");
  lang.add("c");//not added
  System.out.println(lang);
  lang.add("C++");
  lang.remove("J2ee");
  System.out.println("Now Set: "+lang);
 }
}

Expected Output

[python, java, c, J2ee]
Now Set: [python, C++, java, c]

Explanation of the Program

  • A HashSet is backed by a Hash Table data structure.
  • It is the fastest type of Set for basic operations (add, remove, contains). However, it makes no guarantees whatsoever regarding the order of the elements. The elements will print in a seemingly random order based on their generated Hash Codes.
  • When you attempt to add a duplicate element, the HashSet detects the identical hash code, realizes the object already exists, and silently rejects the addition.

Complexity

Time Complexity O(1) - Constant time performance for basic operations.
Space Complexity O(n)
ADVERTISEMENT