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
It doesnot give complier
why so ?
1. abc is sort in the output based on the key. It uses the key to sort its values. and the Integer is used as the key for the TreeMap object.
2. Because they are different objects. the subMap() method returns a SortedMap object which cannot be casted to a TreeMap.
3. Since Iterator is a generic class, you need to specify the object type or you class it. That is
or in the while loop you cast it to Integer that is,
Integer aa = (Integer)it.next();
Why the System.out.println(it.next()) worked is because it returns an Object class type and the println() method gives a call to its toString() method
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!!
It is the issue with static inner class TreeMap$AscendingSubMap inside TreeMap<K,V> .
mohitkumar gupta wrote:SortedMap cannot be casted to TreeMap but
SortSet can be casted to TreeSet.
how this possible ?
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.
Check the API for TreeMap<K,V>
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.
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!