Java Collections Framework: Which statement accurately describes java.util.HashSet?
-
AThe elements in the collection are ordered.
-
BThe collection is guaranteed to be immutable.
-
CThe elements in the collection are guaranteed to be unique.
-
DThe elements in the collection are accessed using a unique key.
-
EIt preserves insertion order by default.
Answer
Correct Answer: The elements in the collection are guaranteed to be unique.
Explanation
Introduction / Context: HashSet is a fundamental collection type in Java that stores unique elements backed by a hash table. Understanding its characteristics—uniqueness, ordering, and mutability—is essential for correct API usage.
Given Data / Assumptions:
- We refer to the standard
java.util.HashSetbehavior. - Default settings are assumed (no explicit
LinkedHashSetorTreeSet).
Concept / Approach: A HashSet contains no duplicate elements; it uses hash codes to place elements in buckets. It does not maintain any specific iteration order (in contrast to LinkedHashSet which preserves insertion order). It is mutable by default. It does not provide key-based access like Map types; it stores elements, not key–value pairs.
Step-by-Step Solution:
Uniqueness: enforced by equals()/hashCode() semantics → True.Ordering: iteration order is unspecified and can change with rehashing → Not ordered.Mutability: supports add/remove/clear → Not immutable.Key access: pertains to maps (HashMap), not sets → Not applicable.Verification / Alternative check: Javadoc for HashSet states it makes no guarantees as to the iteration order and permits null elements (at most one).
Why Other Options Are Wrong:
- Ordered: not guaranteed by
HashSet. - Immutable: false—
HashSetis mutable. - Access by unique key: describes maps, not sets.
- Preserves insertion order: that is
LinkedHashSet, notHashSet.
Common Pitfalls: Assuming iteration order remains stable; resizing or different JVMs can produce different orders. Use LinkedHashSet if stable insertion order is required.
Final Answer: The elements in the collection are guaranteed to be unique.