简体   繁体   中英

Difference between these declaration of TreeSet

So I have to use a TreeSet in my code.

As TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable

and interface NavigableSet<E> extends SortedSet<E> which extends Set<E>

I can use any of these three declaration:

NavigableSet<String> myTreeSet= new TreeSet<>();
SortedSet<String> myTreeSet= new TreeSet<>();
Set<String> myTreeSet= new TreeSet<>();

I know I will be having access to only those method which are exposed by the Interface I am using in the declaration. Is there any other reason to consider for selecting a particular declaration for a TreeSet ?

its basically what you allow others (or yourself) to use, as you are stated. Other methods you like to use with your TreeSet might depend on the actual declaration. So there might be a method requiring a SortedSet, but when you define your TreeSet as Set, it will not be able to proceed

You should use which ever interface you like to program. But what makes the difference is to which interface you are programming . I mean, programming to an interface (declaration type) and not to the actual TreeSet collection.

Here is the best answer which explains Programming to an interface .

Please, don't make preliminary decisions. If you don't need methods from NavigableSet don't use it. Just use Set<String> .

As a guiding rule always choose the most top level type possible because this allows greater decoupling from the client code towards the concrete implementation. Most of the time it is not important to the calling code to know which implementation is used, you just want to provide the behaviour not expose it. Said that, sometimes you will feel like needing a little more control, then you should go through the interfaces hierarchy until you find the necessary level of control, but this should be the exception, not the rule

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