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 Standardimport 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 internalHashMap, with a dummy constant as the Value. - Since keys in a
HashMapmust be unique, this ensures the property of theSet.
β Common mistakes
- Custom Objects: Forgetting to override
equals()andhashCode()for custom objects stored in aHashSet. - Order Assumption: Assuming that
HashSetwill maintain insertion order (useLinkedHashSetif 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).