| Author |
Casting in Collection
|
Kir Swa
Greenhorn
Joined: May 03, 2012
Posts: 8
|
|
import java.util.*;
public class Navcas
{
public static void main(String[] args)
{
SortedMap<Integer,String> nv= new TreeMap<Integer,String>();
nv.put(1,"one");
nv.put(2,"two");
nv.put(3,"three");
nv.put(4,"four");
SortedMap ns=nv.subMap(1, 4);
SortedSet t=(SortedSet)nv.keySet();//Line1
Set c= (Set)nv.values();//Line2
System.out.println(t);
System.out.println(c);
System.out.println(ns.size());
}
}
In line1 KeySet() returns Set and it typecast to SortedSet its working fine, but in Line2 values() returns Collection but why Collection is not casting to Set/SortedSet?
Can any one help me on this?
|
 |
gurpeet singh
Ranch Hand
Joined: Apr 04, 2012
Posts: 891
|
|
Kir Swa wrote:import java.util.*;
public class Navcas
{
public static void main(String[] args)
{
SortedMap<Integer,String> nv= new TreeMap<Integer,String>();
nv.put(1,"one");
nv.put(2,"two");
nv.put(3,"three");
nv.put(4,"four");
SortedMap ns=nv.subMap(1, 4);
SortedSet t=( SortedSet)nv.keySet();//Line1
Set c= (Set)nv.values();//Line2
System.out.println(t);
System.out.println(c);
System.out.println(ns.size());
}
}
In line1 KeySet() returns Set and it typecast to SortedSet its working fine, but in Line2 values() returns Collection but why Collection is not casting to Set/SortedSet?
Can any one help me on this?
nv.values return an object which IS-A Collection , which is supertype of all the collection classes. you cannot cast supertype object to subtype.
|
OCPJP 6(100 %) OCEWCD 6(91 %)
|
 |
Dan Drillich
Ranch Hand
Joined: Jul 09, 2001
Posts: 1126
|
|
The compiler says -
The hierarchy is -
java.lang.Object
-java.util.AbstractMap<K,V>
--java.util.TreeMap<K,V>
So, java.util.TreeMap can't get cast to java.util.Set.
Regards,
Dan
|
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
|
 |
Dan Drillich
Ranch Hand
Joined: Jul 09, 2001
Posts: 1126
|
|
About -
keySet()
Returns a Set view of the keys contained in this map.
Regards,
Dan
|
 |
 |
|
|
subject: Casting in Collection
|
|
|