Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the keySet() of a SortedMap always be cast safely to a SortedSet?

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?

like image 707
Andrew Stein Avatar asked Sep 14 '12 15:09

Andrew Stein


People also ask

What is SortedSet and SortedMap?

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.

Is keySet sorted in TreeMap?

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.

Is keySet sorted in Java?

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.

How do I get TreeMap keySet?

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.


1 Answers

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();
like image 61
assylias Avatar answered Sep 20 '22 14:09

assylias