File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Sierra & Bates scjp 6 page 587 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sierra & Bates scjp 6 page 587" Watch "Sierra & Bates scjp 6 page 587" New topic
Author

Sierra & Bates scjp 6 page 587

Richard Hayward
Ranch Hand

Joined: Feb 15, 2012
Posts: 54
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

Joined: Mar 05, 2008
Posts: 2969
    
    9
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

Joined: Feb 15, 2012
Posts: 54
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sierra & Bates scjp 6 page 587
 
Similar Threads
Collections-Getting error, using subList(fromIndex, toIndex) in List!
How can we return a interface?
ClassCastException using Treemap.headMap()
Casting in Generics, is it redundant?
Casting Differences - Collections