This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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 Java Interview Guide this week in the Jobs Discussion 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

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 ?

Akash Singh
Henry Wong

Joined: Sep 28, 2004
Posts: 20538

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.


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

Joined: Apr 20, 2009
Posts: 808

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.

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 .

TreeMap submap =new TreeMap();

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:
subject: return type of headSet and headMap methods.
It's not a secret anymore!