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,
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.