Question statement:
Suppose that you need to work with a collection of elements that need to be sorted in their natural order, and each element has a unique text id that you want to use to store and retrieve the record.
Which of the following collections classes in the java.util package best suits your needs for this scenario?
A. ArrayList
B. HashMap
C. HashSet
D. TreeMap
E. TreeSet
F. None of the above
The
test says the correct answer is D. I think the correct answer should be E because none of the data structures on the list satisfy what the problem statement is asking.
Elements that need to be sorted in their natural order -> means
1. The elements must implement Comparable
2. No custom Comparator is allowed when creating TreeMap
3. Since TreeMap only sorts its keys, the elements themselves must be used as keys, and not their uniqueID.
Each element has a unique text id that you want to use to store and retrieve the record -> means
1. This statement most likely means that we now want to conveniently retrieve the element by specifying its uniqueID on retrieval. But then this contradicts with the statement above, which requires that the keys being the element themselves.
2. The only way to retrieve the element we want by specifying the uniqueID now would be to loop through all the entries, which is not efficient at all, and other answers such as ArrayList or HashSet can do the same thing.
To achieve what the question is asking, we need a data structure that sorts its values by natural order(as defined by Comparable) and the keys being unique Ids.
Code I used to test: