Java HashSet
Master membership testing and duplicate removal using one of Java's most powerful collection classes.
What Is a HashSet?
A HashSet is a collection that stores unique elements with no guaranteed order. It implements the Set interface and uses a hash table internally for blazing-fast lookups.
Why Use a HashSet?
Two common problems in programming are checking whether a value exists in a collection and removing duplicate entries. A HashSet solves both efficiently.
Whenever you need fast membership testing ("Is this value in my collection?") or need a collection that automatically prevents duplicates, reach for a HashSet.
How Hashing Works
Core Operations
// Import import java.util.HashSet; // Create HashSet<String> colors = new HashSet<>(); // Add elements colors.add("red"); // true colors.add("blue"); // true colors.add("red"); // false (duplicate!) // Check membership colors.contains("blue"); // true colors.contains("green");// false // Remove & size colors.remove("red"); // true colors.size(); // 1
Time Complexity
| Operation | HashSet | ArrayList |
|---|---|---|
| add(element) | \( O(1) \) | \( O(1) \) amortized |
| contains(element) | \( O(1) \) | \( O(n) \) |
| remove(element) | \( O(1) \) | \( O(n) \) |
| Get by index | Not supported | \( O(1) \) |
| Maintains order | No | Yes |
HashSet vs. TreeSet vs. LinkedHashSet
How to Apply HashSet
HashSet<Type> using wrapper classes for primitives (Integer, not int).add() in a loop or pass a collection to the constructor.for-each loop, but remember: order is unpredictable.Example 1: Removing Duplicates
Given an array with duplicates, produce a collection of unique values.
int[] nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3}; HashSet<Integer> unique = new HashSet<>(); for (int n : nums) { unique.add(n); } System.out.println(unique); // [1, 2, 3, 4, 5, 6, 9] (order may vary) System.out.println(unique.size()); // 7
Example 2: Membership Testing
Check which words from a user's list appear in a dictionary.
HashSet<String> dict = new HashSet<>(); dict.add("apple"); dict.add("banana"); dict.add("cherry"); String[] words = {"apple", "grape", "cherry"}; for (String w : words) { if (dict.contains(w)) { System.out.println(w + " found!"); } else { System.out.println(w + " NOT found"); } }
Example 3: Finding Common Elements
Find elements that appear in both of two arrays (set intersection).
int[] a = {1, 2, 3, 4, 5}; int[] b = {4, 5, 6, 7, 8}; HashSet<Integer> setA = new HashSet<>(); for (int x : a) setA.add(x); ArrayList<Integer> common = new ArrayList<>(); for (int x : b) { if (setA.contains(x)) { common.add(x); } } // common = [4, 5]
Set Operations in Java
Java's Set interface provides built-in methods for common set algebra:
import java.util.Arrays; import java.util.HashSet; HashSet<String> set1 = new HashSet<>( Arrays.asList("X", "Y", "Z")); HashSet<String> set2 = new HashSet<>( Arrays.asList("Y", "Z", "W")); // Union: set1 ∪ set2 HashSet<String> union = new HashSet<>(set1); union.addAll(set2); // union = {W, X, Y, Z} // Intersection: set1 ∩ set2 HashSet<String> intersection = new HashSet<>(set1); intersection.retainAll(set2); // intersection = {Y, Z} // Difference: set1 − set2 HashSet<String> difference = new HashSet<>(set1); difference.removeAll(set2); // difference = {X}
Iterating a HashSet
HashSet<String> fruits = new HashSet<>(); fruits.add("apple"); fruits.add("mango"); fruits.add("kiwi"); // Enhanced for-loop for (String f : fruits) { System.out.println(f); } // Using an Iterator Iterator<String> it = fruits.iterator(); while (it.hasNext()) { String f = it.next(); if (f.equals("mango")) it.remove(); // safe removal }
hashCode and equals Contract
For custom objects to work correctly in a HashSet, you must override both hashCode() and equals().
Common Mistakes
Question 1 of 5
What is the average time complexity of contains() on a HashSet?
Question 2 of 5
What does add() return when you try to add a duplicate element to a HashSet?
Question 3 of 5
Consider this code:
HashSet<Integer> s = new HashSet<>();
s.add(5); s.add(3); s.add(5); s.add(1); s.add(3);
System.out.println(s.size());
What value does s.size() print?
Question 4 of 5
Which Set implementation preserves insertion order?
Question 5 of 5
You have an ArrayList of 10,000 names and need to check if a given name exists. Which approach is most efficient?