• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sierra & Bates scjp 6 page 587

 
Richard Hayward
Ranch Hand
Posts: 114
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to understand an example from k&b concerning TreeSets using only Java 5 code.
Cutting out the bits that are not relevant here, the code looks like this:



I don't understand line 18.
The docs say that TreeSet<Integer>.headSet() will return a SortedSet<Integer>
yet apparently it's acceptable to cast that returned object to a TreeSet
Just because an object implements the SortedSet<Integer> interface, how does that guarantee that its castable to a TreeSet?
Would it not be possible to construct somehow an object implementing SortedSet<Integer> that isn't so castable?
Or, does this line of code rely on some insider knowledge, beyond what's available in the docs, that TreeSet<Integer>.headSet() will actually return a TreeSet?

Thanks for any help,

Richard


 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seems like a bad practice to me. As far as I know there's no documented reason to expect headSet() to return a TreeSet here. In practice that is what TreeSet does, and it's possible to determine this either by experiment or by reading the source code. But it seems bad practice to depend on this. Better to simply declare the type as SortedSet everywhere - or, since JDK 1.6, NavigableSet, which is an improved version of SortedSet that TreeSet also implements.
 
Richard Hayward
Ranch Hand
Posts: 114
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Simmons wrote:Seems like a bad practice to me. As far as I know there's no documented reason to expect headSet() to return a TreeSet here. In practice that is what TreeSet does, and it's possible to determine this either by experiment or by reading the source code. But it seems bad practice to depend on this. Better to simply declare the type as SortedSet everywhere - or, since JDK 1.6, NavigableSet, which is an improved version of SortedSet that TreeSet also implements.


Thanks for your comments Mike.
Seems I was justified in being uneasy.

Regards

Richard
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic