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。