Given the code fragment:

public class Foo {

    public static void main(String[] args) {
        Map<Integer, String> unsortMap = new HashMap<>();
        unsortMap.put(10, "z");
        unsortMap.put(5, "b");
        unsortMap.put(1, "d");
        unsortMap.put(7, "e");
        unsortMap.put(50, "j");
        Map<Integer, String> treeMap = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        treeMap.putAll(unsortMap);
        for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
            System.out.print(entry.getValue() + " ");
        }
    }
}

What is the result?

A. A compilation error occurs.

B.

d b e z j

C.

j z e b d

D.

z b d e j

題解

TreeMap 實作了 SortedMap 介面,所以存在 TreeMap 的項目元素是經過排序的。在實體化 TreeMap 物件的時候可以傳入自訂的 Comparator 物件來決定項目元素間比較大小的方式,但排序的依據是項目的 key,而不是 value。在這個題目中型態為 Integer 的 key,比較大小的方式為反序排列,也就是說,數值愈大的會愈在前面。例如:1 會在 0 之前,2 會在 1 之前。

所以這題答案為選項 C。