Collections Framework
Set Interface
Analyze the Set interface contract, duplicate prevention invariants, and algebraic set operations.
Interview: Focuses on mathematical set operations, duplicate rejection behavior, and comparisons with List.
The java.util.Set interface represents a collection that contains no duplicate elements. It models the mathematical set abstraction and inherits all its methods directly from Collection.
Duplicate Prevention
Enforces uniqueness: calling add(e) returns false if an element e2 exists such that Objects.equals(e, e2).
Algebraic Ops
Bulk operations map to mathematical set operations: addAll (union), retainAll (intersection), and removeAll (difference).
Immutability Factory
Java 9 provides static factory methods like Set.of(elements), producing unmodifiable and null-hostile Set instances.
Set Identity and Operations
The Set contract depends heavily on element equality:
- Elements added to a Set must implement
equals()andhashCode()correctly to prevent duplicates. - Set.of Null Policy: Unlike traditional sets, immutable sets created via
Set.of(...)throwNullPointerExceptionif null elements are passed. They also throwIllegalArgumentExceptionif duplicate inputs are supplied.
Common Pitfalls
- Mutating elements in a Set: Modifying fields of an element already stored in a Set, which changes its hashcode. This leaves the element lost in the bucket structure, causing leaks.
- Passing duplicates to Set.of: Calling
Set.of("A", "A"), which crashes with anIllegalArgumentExceptionat runtime.
Best Practices
- Ensure Immutability: Prefer storing immutable keys or objects inside a Set to ensure their hashcodes never change.
- Check duplicate returns: Always inspect the return value of
set.add(e)if duplicate detection is part of the program's business logic.
Interview-Relevant Information
Q1: How does Set determine if two elements are duplicates?
Answer: It relies on the element's equals(Object) implementation. If e1.equals(e2) returns true, the Set rejects the second element. For performance, hash-based sets first compare hashCode() values to narrow down candidates.
Q2: What happens if you add duplicates to Set.of()?
Answer: Unlike standard sets (which discard duplicates), the immutable factory method Set.of(...) throws an IllegalArgumentException to alert developers of duplicate hardcoded inputs.
Quick Checklist
Can you state what method Set uses to check for duplicates, name the exception thrown by Set.of when passed duplicate values, and list three set operations? If yes, you understand Set interface.
Use Cases
De-duplicating lists of IDs returned from file reads or network calls.
Performing set intersections to find shared tags across multiple products.
Common Mistakes
Mutating element field states after they have been added to a Set.
Adding duplicate literal parameters into static Set.of constructor arguments.