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?
The answer is in your question; SortedMap and SortedSet are interfaces. They define methods and properties, but they don't actually implement them, so they don't provide any functionality. TreeMap and TreeSet are implementations of these interfaces.
Since a TreeMap implements NavigableMap interface, it has the functionalities of both the NavigableMap as well as the SortedMap . A TreeMap is always sorted based on keys.
The keySet() method of SortedMap Interface in Java is used to create a set out of the key elements contained in the treemap. It basically returns a set view of the keys or we can create a new set and store the key elements in them in an ascending order.
Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object. Convert the entry set to an array using the toArray() method. And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method.
For SortedMap
in general, no as it is not documented in the javadoc.
However, TreeMap
also implements NavigableMap
, which uses a NavigableSet
as a key set and NavigableSet
extends SortedSet
...
So what you can do is:
NavigableMap<K, V> map = ...; //can be a TreeMap or a ConcurrentSkipListMap
SortedSet<K> set = map.navigableKeySet();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With