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

Given the code fragment:

public class Foo {

public static void main (String [ ] args) {

Map unsortMap = new HashMap< > ( );

unsortMap.put (10, "z");

unsortMap.put (5, "b");

unsortMap.put (1, "d");

unsortMap.put (7, "e");

unsortMap.put (50, "j");

Map treeMap = new TreeMap (new

Comparator ( ) {

@Override public int compare (Integer o1, Integer o2) {return o2.compareTo

(o2); } } );

treeMap.putAll (unsortMap);

for (Map.Entry entry : treeMap.entrySet () ) {

System.out.print (entry.getValue () + " ");

}

}

}

What is the result?

    Correct Answer: C

    The code creates an unsorted HashMap with several key-value pairs and then transfers these entries into a TreeMap. The TreeMap uses a custom Comparator to sort its keys. The custom Comparator uses o2.compareTo(o1), which sorts the keys in descending order. Therefore, iterating through the TreeMap's entries will print the values corresponding to the keys sorted in descending order: 50, 10, 7, 5, 1. This results in the output: j z e b d.

Discussion
Svetleto13Option: B

Its B,tested with return o1.compareTo(o2).If you test it with return o2.compareTo(o2) answer is C.

Svetleto13

I meant return o2.compareTo(o1) for answer C

HuimOption: A

a single z will be printed if with return o2.compareTo(o2); While a TreeMap cannot contain duplicate keys.

fffffOption: B

answer B: d b e z j tested; note the typo, it must be return o1.compareTo(o2);

steefaandOption: C

C is correct as o2.compareTo(o1) sorts keys in descending order.

duydnOption: C

C is correct. Sort is DESC( I think this is a typo )

mevltOption: C

The answer is C. I believe there is a typo in compare method. The second o2 should be o1. Otherwise it only prints single z which makes no sense.