The best thing to do would be to look at actual code of TreeMap
(this is from java 1.7):
public Set<K> keySet() {
return navigableKeySet();
}
public NavigableSet<K> navigableKeySet() {
KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
}
And here's the KeySet
class declaration:
static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {...}
As you can see, TreeMap#keySet
method returns a type Set
which is a super interface of NavigableSet
. And the Set
reference returned from it points to a KeySet
instance, as in navigableKeySet()
method.
And since KeySet
class implements NavigableSet
, you can always cast a reference pointing to it's instance to a NavigableSet
reference.
Just to make sure that you are independent of keySet()
method implementation you could simply call navigableKeySet()
method to get NavigableSet
and avoid the cast