Java SE 8 Programmer II — Question 97
Given the code fragment:
Map<Integer, String> books = new TreeMap<>();
books.put (1007, "A");
books.put (1002, "C");
books.put (1003, "B");
books.put (1003, "B");
System.out.println (books);
What is the result?
Answer options
- A. {1007=A, 1003=B, 1002=C}
- B. {1007=A, 1003=B, 1003=B, 1002=C}
- C. {1007=A, 1002=C, 1003=B, 1003=B}
- D. {1002=C, 1003=B, 1007=A}
Correct answer: D
Explanation
The correct answer is D because a TreeMap sorts the keys in natural order, which means the output will display the entries in ascending order of the keys. Options A, B, and C are incorrect as they do not reflect the correct sorted order of the keys.