Core Module
12 min forge

HashSet in Java

Unique element storage, internal working with HashMap, and performance.

HashSet in Java

πŸ“˜ What is it

HashSet is a collection that contains no duplicate elements. It is part of the java.util package and implements the Set interface. It is backed by a HashMap internally.

⚑ When to use

Use HashSet when you need to store unique elements and do not care about the order of insertion. Typical use cases include filtering duplicates or membership testing.

🧠 Time complexity

  • Add: $O(1)$ (average case)
  • Remove: $O(1)$ (average case)
  • Contains (Search): $O(1)$ (average case)

πŸ’» Code example

java Standard
import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { Set<Integer> uniqueIds = new HashSet<>(); uniqueIds.add(101); uniqueIds.add(102); uniqueIds.add(101); // Duplicate, will not be added System.out.println("Set size: " + uniqueIds.size()); // 2 } }

πŸ—οΈ Internal Working

HashSet uses an internal HashMap to store its elements.

  • When an element is added to a HashSet (e.g., set.add(value)), it is actually added as a Key in the internal HashMap, with a dummy constant as the Value.
  • Since keys in a HashMap must be unique, this ensures the property of the Set.

❌ Common mistakes

  • Custom Objects: Forgetting to override equals() and hashCode() for custom objects stored in a HashSet.
  • Order Assumption: Assuming that HashSet will maintain insertion order (use LinkedHashSet if order is needed).
  • Modification: Modifying an object after it has been added to the set in a way that changes its hashCode (this can "lose" the object in the set).