Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return type of headSet and headMap methods.

 
akaash singh
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21500
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.




 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic