I have a SortedMap, ordered according to the natural ordering of its keys. Can I safely cast its keySet() to a SortedSet, without risking an invalid cast exception.
That is, will the following throw?
SortedMap<K, V> map = ...;
SortedSet<K> set = (SortedSet<K>) map.keySet();
If the answer is “depends on the implementation of SortedMap”, is this at a minimum safe for a TreeMap?
For
SortedMapin general, no as it is not documented in the javadoc.However,
TreeMapalso implementsNavigableMap, which uses aNavigableSetas a key set andNavigableSetextendsSortedSet…So what you can do is: