Exams Knowledge Hub

MCQs for Competitive Exams, School & College Exams

Module: | Arrays, Strings & Exception Handling

Q60: Consider the following statements regarding HashSet and TreeSet:

1. HashSet internally instantiates and utilizes a HashMap to store its elements, explicitly inserting the Set elements as keys and a static dummy object as the values.
2. TreeSet guarantees an ultra-fast O(1) constant time complexity for fundamental operations such as add, remove, and contains.
3. TreeSet automatically sorts its elements into a naturally ascending sequence by physically implementing a self-balancing Red-Black Tree data structure.

Which of the above statements is/are correct?
A
Only 1 and 2
B
Only 1 and 3
C
Only 2 and 3
D
1, 2, and 3
✅ Correct Answer: B
🎯 Quick Answer:
The correct combination is 1 and 3. Statement 2 is incorrect because the Red-Black Tree architecture of TreeSet dictates an O(log n) time complexity for basic operations, not O(1).
Concept Definition: Set implementations are data structures that strictly prohibit duplicate elements.
HashSet relies on hashing for maximum speed, whereas TreeSet relies on binary trees for guaranteed sorting.
Structural Breakdown: HashSet = Unordered, accepts one null, O(1) time complexity.
TreeSet = Sorted (natural or custom comparator), rejects nulls, O(log n) time complexity.
Historical/Related Context: The architectural reuse of HashMap to build HashSet (Statement 1) was a brilliant engineering shortcut by Java's creators.
Because HashMap already possessed a perfectly optimized algorithm for preventing duplicate keys, the creators simply wrapped a HashMap inside the HashSet class and fed all added elements directly into the key parameter.
Causal Reasoning: TreeSet rejects null elements because it must continuously compare every new element against existing elements using the compareTo() method to determine left/right tree placement.
Attempting to invoke compareTo() on a null reference instantly triggers a fatal NullPointerException, breaking the tree's balancing algorithm.