Exam 1z0-809 All QuestionsBrowse all questions from this exam
Question 175

Given the code fragment:

Map 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?

    Correct Answer: D

    The TreeMap implementation of the Map interface in Java automatically sorts the entries by their natural ordering of keys, which in this case are integers. When inserting the entries (1007, 'A'), (1002, 'C'), and (1003, 'B') into the TreeMap, they will be stored in ascending key order. Furthermore, duplicate keys are not allowed in a Map, so the second insertion of (1003, 'B') does not change the map. As a result, the entries will be ordered by their keys as {1002='C', 1003='B', 1007='A'}.

Discussion
jduarteOption: D

Answer D, tester

steefaandOption: D

D is true as TreeMap sorts in natural order by key. Also if last line of insertion was replaced by books.put (1003, "D"); then that would be printed.

duydnOption: D

D is correct, TreeMap sort by natural : key