简体   繁体   中英

.tailSet supposedly returns NavigableSet, but seems to return TreeSet

This may seem like a weird question but I'm a little confused: In Java, the method NavigableSet.tailSet(Object) supposedly returns a SortedSet, and tailSet(Object, boolean) returns a NavigableSet. But it seems to me like they actually both return a TreeSet.

TreeSet<String> mts= new TreeSet<String>();
Object whatTypeAmI = mts.tailSet("bla");

I mean...

  • The oracle pages say tailSet(Object) returns a SortedSet and tailSet(Object, boolean) a NavigableSet
  • When I hover my mouse over the methods in Eclipse it says so too
  • The fact that you can't directly assign the result of tailSet(String) to a NavigableSet without casting it supports this as well

BUT:

  • When I run a code in debug mode and examine mts.tailSet("bla"), it tells me it's a variable of type TreeSet
  • mts.tailSet("bla").getClass() returns TreeSet
  • mts.tailSet("bla") instanceof TreeSet returns true.

Why is that?

EDIT:

I know that TreeSet implements NavigableSet which extends SortedSet which extends Set. I know it makes sense for a TreeSet to be recognized as a NavigableSet. But a NavigableSet shouldn't be recognized as a TreeSet.

The point of this question isn't so much practical use as it is theoretical. (I'm studying for a test. I need to be able to tell if code will compile or not). If tailSet returns a TreeSet, then how come this doesn't compile?

TreeSet<String> tree = mytreeset.tailSet("xx");

Why do I need to add a cast to TreeSet?

NavigableSet and SortedSet are both interfaces that are implemented by TreeSet . Both methods could also return a ConcurrentSkipListSet if they wanted to since it also implements both interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM