01 / 20

Java HashSet

Master membership testing and duplicate removal using one of Java's most powerful collection classes.

Java Collections Framework

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.

No Duplicates
Adding an element that already exists is silently ignored.
Unordered
Elements are not stored in insertion order or sorted order.
Null Allowed
A HashSet permits one null element.

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

Values "cat" "dog" "bat" "cat" duplicate! hashCode() Buckets [0] "cat" [1] empty [2] "dog" [3] empty [4] "bat" rejected (already in [0]) Each value hashes to a bucket index. Duplicates are detected and rejected.

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

HashSet
Fastest operations. No ordering guarantee. Best for pure membership testing.
TreeSet
Sorted order. \( O(\log n) \) operations. Use when you need elements in natural order.
LinkedHashSet
Insertion order preserved. Slightly slower than HashSet. Use when order matters.

How to Apply HashSet

1
Identify the need: Do you need fast lookups or uniqueness? If yes, use a HashSet.
2
Declare with the right type: HashSet<Type> using wrapper classes for primitives (Integer, not int).
3
Populate the set: Use add() in a loop or pass a collection to the constructor.
4
Query with contains(): Check membership in \( O(1) \) average time.
5
Iterate if needed: Use a 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().

1
If a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true.
2
If you override equals(), you must override hashCode(). Otherwise the HashSet cannot find your object.
3
Two unequal objects may share the same hash code (collision): that's fine, but hurts performance.

Common Mistakes

✕ Using int Instead of Integer
Generics require wrapper classes. HashSet<int> won't compile: use HashSet<Integer>.
✕ Assuming Order
HashSet does not maintain insertion order. If order matters, use LinkedHashSet.
✕ Removing During For-Each
Calling set.remove() inside a for-each loop throws ConcurrentModificationException. Use an Iterator.
✕ Missing hashCode Override
Custom objects need both equals() and hashCode() overridden, or duplicates sneak in.

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

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?