What will be the output of the following code, assuming all imports are in place and the code is inside a main method?

NavigableMap<String, String> nm = new TreeMap<String, String>();
nm.put("1", "one");
nm.put("3", "three");
nm.put("2", "two");
nm.put("4", "four");

NavigableSet<String> keys = nm.keySet();
NavigableSet<String> subKeys = keys.subSet("1", true, "3", false);

for(String s: subKeys) {
    System.out.print(s + " ");
This code will fail to compile. The keySet() method will return a Set. Set is a superclass of NavigableSet, hence it is-not-a NavigableSet (we've got exactly the opposite: a NavigableSet is-a Set). An explicit cast would fix the code through: (NavigableSet<String>) nm.keySet();

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback