Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 44
Question ID: UKOCP35329
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.util.*;
- enum TrafficLight {
- RED, YELLOW, GREEN
- }
- public class Test {
- public static void main(String[] args) {
- Map<TrafficLight, String> map = new TreeMap<>();
- map.put(TrafficLight.GREEN, "GO");
- map.put(TrafficLight.RED, "STOP");
- map.put(TrafficLight.YELLOW, "READY TO STOP");
- for(String msg : map.values()) {
- System.out.println(msg);
- }
- }
- }
What will be the result of compiling and executing Test class?
-
A
STOP
READY TO STOP
GO
-
B
GO
STOP
READY TO STOP
-
C
GO
READY TO STOP
STOP
- D Printing order cannot be predicted
Reveal correct answer
Correct answer: A
Explanation
UKOCP35329:
TreeMap is the sorted map on the basis on natural ordering of keys (if comparator is not provided).
enum TrafficLight is used as a key for TreeMap. The natural order for enum elements is the sequence in which they are defined. Value corresponding to 'RED' is printed first, followed by value corresponding to 'YELLOW' and finally value for 'GREEN' is printed.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
