wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting in Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting in Collection" Watch "Casting in Collection" New topic
Author

Casting in Collection

Kir Swa
Greenhorn

Joined: May 03, 2012
Posts: 9
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: 924
    
    1

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.
Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1169
The compiler says -
Exception in thread "main" java.lang.ClassCastException: java.util.TreeMap$Values cannot be cast to java.util.Set at Navcas.main(Navcas.java:15)


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: 1169
About -



keySet()
Returns a Set view of the keys contained in this map.


Regards,
Dan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting in Collection
 
Similar Threads
Doubt on subMap() in NavigableMap
AutoBoxing&generic
Want to write a combined text file, but nothing happens..
Generics for ArrayList
primitive casting