Java•Sets
Java HashSet: Deduplication and Unique Sets
Learn how HashSet eliminates duplicate elements and delivers O(1) membership testing with contains().
Syntax
HashSet<String> set = new HashSet<>();
set.add("A");
boolean hasA = set.contains("A");
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| HashSet<T> | Set Collection | Backing hash table storing unique items. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Java locally:
import java.util.HashSet;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Automatic deduplication of input list
HashSet<String> allowedRoles = new HashSet<>(
Arrays.asList("ADMIN", "DEVELOPER", "REVIEWER", "ADMIN")
);
System.out.println("Unique Roles: " + allowedRoles);
System.out.println("Total Roles: " + allowedRoles.size());
// Fast O(1) membership check
System.out.println("Contains ADMIN? " + allowedRoles.contains("ADMIN"));
System.out.println("Contains GUEST? " + allowedRoles.contains("GUEST"));
}
}Expected Output:
Unique Roles: [REVIEWER, DEVELOPER, ADMIN] Total Roles: 3 Contains ADMIN? true Contains GUEST? false
How It Works: Step-by-Step
- Lines 6-8: Deduplicates input list ("ADMIN" added twice, stored once).
- Lines 14-15: contains() performs fast hash table lookup.
Key Concepts
- HashSet allows at most one null element and guarantees uniqueness.
- Custom objects in HashSet must properly override equals() and hashCode().
- TreeSet stores elements in natural sorted order.
Common Mistake: Using custom class in HashSet without overriding equals() and hashCode()
Without hashCode/equals, distinct instances with identical fields are treated as different objects.
❌ Incorrect
class User { int id; } // Duplicate User objects will both be stored!✅ Correct
// Override equals() and hashCode() on id field
Related Java Tutorials & Compiler
Java ArrayList and Arrays: Dynamic Collections vs Fixed Arrays
Master fixed-size arrays and dynamic java.util.ArrayList with add, get, and remove.
Java HashMap: Key-Value Mapping and Collections
Store and retrieve key-value pairs using java.util.HashMap with O(1) performance.
Java String Methods, StringBuilder, and Immutability
Master String methods (split, substring, replace) and mutable StringBuilder for performance.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.