Back to Study Material Java

Set Interface in Java

The Set interface extends Collection and enforces a single rule: no duplicate elements. Uniqueness is defined by the equals method. Two objects a and b are...

Set Interface in Java

Uniqueness Guarantee and Core Contract

The Set interface extends Collection and enforces a single rule: no duplicate elements. Uniqueness is defined by the equals method. Two objects a and b are considered duplicates if a.equals(b) returns true. Consequently, any class whose instances you store in a Set must have a well-defined, consistent equals implementation, and by the Java contract, objects that are equal must also return the same hashCode value.

Set defines the same methods as Collection with this uniqueness constraint layered on top. The add(E e) method returns true if the element was actually inserted and false if it was already present, which differs from Collection where add always returns true on success. This return value lets callers detect whether a new element was contributed.

Set does not add index-based access methods because sets are not ordered by position. Access is only through iteration, contains checks, or bulk operations like retainAll (intersection), addAll (union), and removeAll (difference).

Mathematical Set Operations

The three classic set operations map directly to Collection methods. Union: Set<T> union = new HashSet<>(setA); union.addAll(setB); Intersection: Set<T> intersection = new HashSet<>(setA); intersection.retainAll(setB); Difference: Set<T> difference = new HashSet<>(setA); difference.removeAll(setB); Each of these creates a new set without modifying the originals, assuming you copy setA into a fresh collection first.

These operations are used in many algorithms: finding common friends in a social graph (intersection), merging tag sets (union), or identifying items present in one collection but not another (difference).

The containsAll method checks subset relationships: setA.containsAll(setB) returns true if setB is a subset of setA. Combined with size checks you can test for proper subsets and set equality.

Choosing the Right Set Implementation

Java provides three primary Set implementations with distinct trade-offs. HashSet offers O(1) average for add, remove, and contains, with no guarantees on iteration order. TreeSet maintains elements in sorted natural order (or by a Comparator) at the cost of O(log n) for add, remove, and contains. LinkedHashSet preserves insertion order while keeping O(1) operations, at the expense of extra memory for a doubly linked list threading through the hash buckets.

A brief example: Set<String> uniqueWords = new HashSet<>(); uniqueWords.add("java"); uniqueWords.add("python"); uniqueWords.add("java"); System.out.println(uniqueWords.size()); prints 2 because the second "java" was rejected.

An interview tip: a candidate who knows Set well will mention the equals-hashCode contract without prompting. If you override equals but not hashCode, two logically equal objects may hash to different buckets in a HashSet, causing the set to store both as if they were distinct. This is one of the most common subtle bugs in Java development.