1Z0-809 · Question #78
Given the code fragment: Map<Integer, String> books = new TreeMap<>(); books.put (1007, "A"); books.put (1001, "B"); books.put (1001, "B"); books.put (1003, "B"); System.out.println (books); What is…
The correct answer is B. {1001 = B, 1002 = C, 1003 = B, 1007 = A}. Note: The third put in the code fragment appears to be a typo - it should be books.put(1002, "C") to match the answer choices. The explanation below assumes that correction. Option B is correct because TreeMap automatically sorts its entries by key in natural ascending order…
Question
Options
- A{1007 = A, 1002 = C, 1001 = B, 1003 = B}
- B{1001 = B, 1002 = C, 1003 = B, 1007 = A}
- C{1002 = C, 1003 = B, 1007 = A}
- D{1007 = A, 1001 = B, 1003 = B, 1002 = C}
How the community answered
(59 responses)- A12% (7)
- B78% (46)
- C7% (4)
- D3% (2)
Explanation
Note: The third put in the code fragment appears to be a typo - it should be books.put(1002, "C") to match the answer choices. The explanation below assumes that correction.
Option B is correct because TreeMap automatically sorts its entries by key in natural ascending order, so regardless of insertion order, the output will be {1001=B, 1002=C, 1003=B, 1007=A}. Also, maps do not allow duplicate keys - if the same key were inserted twice, the second value would simply overwrite the first, keeping only four distinct entries.
Why the distractors are wrong:
- A lists the correct entries but in unsorted (insertion-like) order -
TreeMapalways sorts, so this is never valid. - C is missing the
1001=Bentry entirely - there are four distinct keys, so four entries must appear. - D also shows entries in insertion order rather than sorted key order.
Memory tip: Think of TreeMap as a Tidy Map - it always keeps keys Trimmed into sorted order. If you need insertion-order preservation instead, that's LinkedHashMap; if you need no ordering guarantees but raw speed, use HashMap.
Community Discussion
No community discussion yet for this question.