1Z0-809 · Question #53
unSortMap.put (7, "e"); unSortMap.put (50, "m"); Map<Integer, String> treeMap = new TreeMap <Integer, String> (new Comparator<Integer> () { @Override public int compare (Integer o1, Integer o2)…
The correct answer is C. e z b d. Option C is correct because the custom Comparator uses o2.compareTo(o1) instead of the natural o1.compareTo(o2), which reverses the sort order - TreeMap stores entries by descending key rather than ascending. When iterated, the values are printed from the highest key to the…
Question
Options
- AA compilation error occurs.
- Bd b e j
- Ce z b d
- Dz b d e j
How the community answered
(34 responses)- A3% (1)
- B6% (2)
- C85% (29)
- D6% (2)
Explanation
Option C is correct because the custom Comparator uses o2.compareTo(o1) instead of the natural o1.compareTo(o2), which reverses the sort order - TreeMap stores entries by descending key rather than ascending. When iterated, the values are printed from the highest key to the lowest, yielding e z b d.
Why the distractors are wrong:
- A is wrong because the code is syntactically valid Java - anonymous
Comparatorclasses with generics compile without issue. - B (
d b e j) reflects ascending key order (natural TreeMap behavior without the custom Comparator), not the reversed order the code actually applies. - D (
z b d e j) contains five values, suggesting a misread of the map's contents or confusion about which entries are included.
Memory tip: When you see o2.compareTo(o1) in a Comparator, mentally swap the letters - o2 before o1 means the second argument wins, which flips to descending order. Think: "backwards arguments, backwards sort."
Community Discussion
No community discussion yet for this question.