keySet() returns java.util.Set.
Why doesn’t cast to NavigableSet throw a ClassCastException?
This can be if real Object is a TreeSet with the java.util.Set reference. I can`t understand that.
import java.util.*;
class A1{}
public class Main{
public static void main(String args[]){
SortedMap nvs=new TreeMap();
nvs.put(1,"one");
nvs.put(2,"two");
nvs.put(3,"three");
nvs.put(4,"four");
NavigableSet nss=(NavigableSet)nvs.keySet();
for(Object ob: nss){
System.out.print(nvs.get(ob)+", ");
}
}
}
The best thing to do would be to look at actual code of
TreeMap(this is from java 1.7):And here’s the
KeySetclass declaration:As you can see,
TreeMap#keySetmethod returns a typeSetwhich is a super interface ofNavigableSet. And theSetreference returned from it points to aKeySetinstance, as innavigableKeySet()method.And since
KeySetclass implementsNavigableSet, you can always cast a reference pointing to it’s instance to aNavigableSetreference.Just to make sure that you are independent of
keySet()method implementation you could simply callnavigableKeySet()method to getNavigableSetand avoid the cast