Java Program to demonstrate the use of HashSet.
Objective
Write a Java program to demonstrate uniqueness and hashing using a HashSet.
Algorithm / Approach
- Create a
HashSet. - Add several programming languages to the set.
- Attempt to add a duplicate value (e.g., "c" twice).
- Print the set to observe that the duplicate was ignored and the insertion order was NOT preserved.
- 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
HashSetis 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)