Set Semantics and HashSet

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

A set stores unique elements. add ignores duplicates (regarding equals). contains checks for membership. The order is not defined in HashSet.

Typical usage: visited nodes in graph algorithms, deduplication of IDs.

TreeSet maintains a sorted order and requires Comparable or Comparator. HashSet needs correct equals/hashCode.

Edge case: mutable keys that change their hashCode after insertion break the set.

Diagram

Groups of equal signature: Group Anagrams [1].

Where used

Deduplication of IDs, visitor markers in graph algorithms, permission and tag sets, unique constraints in storage. HashSet is the standard choice when only membership counts and no sorting is needed.

Depth

A set models membership without position or duplicate semantics. When inserting an already equal element, the mathematical set remains unchanged. The iteration order is not part of the general contract.

A hash structure calculates a range from the key and only examines candidates in that range more closely. Good scattering keeps these candidate sets small. Collisions are normal and must be handled correctly through chaining or internal tree structures.

Mutable keys are dangerous: If a field relevant for hashing or equality changes after insertion, the object can remain in the wrong range and become logically unfindable.

Difficulty levels

  1. Differentiate set operations from list operations.
  2. Distinguish between collision and equality.
  3. Explain the effects of a mutable key.

Pitfalls

No guarantee can be derived from the observed iteration order. Two different elements with the same hash value remain permissible and must be distinguished through equality checks.


Sources

University approvals: 0
Tasks
Question 1

What happens in HashSet.add if equals reports that the element is already contained?

Question 2

What follows from an identical hash value of two elements?

Question 3

Insert x into the set and return whether x was new.

Hint

Set.add(element) already returns a boolean value. In Set<Integer>, autoboxing handles the conversion from int.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy