Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting in Collection

 
Kir Swa
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 924
1
Fedora Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1183
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dan Drillich
Ranch Hand
Posts: 1183
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic