Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes return type of headSet and headMap methods. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "return type of headSet and headMap methods." Watch "return type of headSet and headMap methods." New topic
Author

return type of headSet and headMap methods.

akaash singh
Ranch Hand

Joined: Jul 04, 2009
Posts: 45
Hi ,
Why is that T s1 = (TreeSet) times1.headSet(1600); works fine whereas m1 =(TreeMap) times2.headMap(1600) gives a class cast exception. s1 and times1 being appropriately initialized TreeSets ; and m1 and times2 being appropriately initialized TreeMaps .

Shouldnt these two maps being corresponding functions of Set and Map collections behave similarly ?

Regards
Akash Singh
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Context Please

What's times1? What's times2? What's headSet()? What's headMap()?

[EDIT: Okay, I see. You are referring to the SortedSet and SortedMap interface]


Anyway, the interface (JavaDoc) states that the method should return a SortedSet and SortedMap respectively. There is nothing defined, that it must return a TreeSet for the SortedSet, and a TreeMap for the SortedMap -- although in the first case, it just happens to.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

It depends on the invokation.
Java6 has the new version of the methods - those with boolean arguments. (see Java API)
Methods with boolean arguments return NavigableXxx and without boolean - SortedXxx, which is super interface of NavigableXxx and you need explicite downcasting.


SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
akaash singh
Ranch Hand

Joined: Jul 04, 2009
Posts: 45
The context was ( an example on page 586 of kathy and bert's book)


I did the same for TreeMap and got a ClassCast Exception .

times.add(123);
...
...
TreeMap submap =new TreeMap();
submap=(TreeMap)times.headmap(150);//say
[/code]

If i declare submap as a SortedMap it works ok , as Henry said .

But why do I need a cast in case of headSet it it indeed returns a TreeSet.




 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: return type of headSet and headMap methods.