1.why is the abc not sorted in output while the treeset def above is sorted in the output ?
2.why is the line 35 giving:
Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap$AscendingSubMap cannot be cast to java.util.TreeMap
3.the code at line 23 ,24 gives complier error,but when i replace the code with
TreeMap.subMap(fromKey, toKey) returns a SortedMap, which cannot be casted to TreeMap.
But TreeMap.subMap(fromKey, boolean includive, toKey, boolean inclusive) returns a NavigableMap!
I changed your code to return a NavigableMap which is including 2 and 3 in subMap.
But you will get a Runtime Exception because you are putting 7 and 9 as keys to the sub map which should contain only keys ranging from 2 to 3. I have commented those lines also. The following code compiles and runs fine!
#1. You can sort only by keyt's in a Map , not by values!!
mohitkumar gupta wrote:SortedMap cannot be casted to TreeMap but
SortSet can be casted to TreeSet.
how this possible ?
It is the issue with static inner class TreeMap$AscendingSubMap inside TreeMap<K,V> .
Either you can use
or if you want to convert SortedMap<K,V> to TreeMap<K, V> there is a special constructor in TreeMap for that.
Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method runs in linear time.
Another simple explanation: Consider two classes Animal and Horse where Animal is the super class and Horse is the sub class which extends Animal
In your code SortedMap<K,V> is the parent interface and TreeMap<K,V> is the child class.
So technically you cannot cast a SortedMap<K,V> instance( or a method which returns SortedMap<K,V>) to TreeMap<K,V> unless the method actually returns a TreeMap<K,V>! Code will compile , but you may get a ClassCastException during runtime.
The reason you are NOT getting issues with SortedSet<K> is that it may be returning a TreeSet(K) ( actual return value) from the subSet() method. I don't know the internals of these classes. You may want to check codejar.com for more details!