简体   繁体   中英

TreeSet in Java

I understand Java best practice suggests that while declaring a variable the generic set interface is used to declare on the left and the specific implementation on the right.

Thus if I have to declare the Set interfaces, the right way is,

Set<String> set = new TreeSet<>();

However with this declaration I'm not able to access the set.last() method. However when I declare it this way,

TreeSet<String> set = new TreeSet<>(); 

I can access, last() and first() . Can someone help me understand why?

The last() and first() are specific methods belonging to TreeSet and not the generic interface Set . When you refer to the variable, it's looking at the source type and not the allocated type, therefore if you're storing a TreeSet as a Set , it may only be treated as a Set . This essentially hides the additional functionality.

As an example, every class in Java extends Object . Therefore this is a totally valid allocation:

final Object mMyList = new ArrayList<String>();

However, we'll never be able to use ArrayList style functionality when referring directly to mMyList without applying type-casting , since all Java can tell is that it's dealing with a generic Object ; nothing more.

您可以使用SortedSet接口作为声明(具有first()last()方法)。

The interface of Set does not provide last() and first() because it does not always make sense for a Set .

Java is a static typing language. When compiler see you doing set.last() , as it is expecting set to be a Set . It will not know whether set is a TreeSet that provides last() , or it is a HashSet that does not. That's why it is complaining.

Hold on. You do not need to declare it using the concrete class TreeSet here. TreeSet bears a SortedSet interface which provides such methods. In another word: because you need to work with a Set that is sorted (for which it make sense to provide first() and last() ), the interface that you should work against should be SortedSet instead of Set

Hence what you should be doing is

SortedSet<String> set = new TreeSet<>();

To add to the existing answers here, the reason is that TreeSet implements the interface NavigableSet which inherits from the interface java.util.SortedSet the methods comparator, first , last and spliterator.

Just the Set , on the other side, doesn't have SortedSet methods because it's not inherit from it.

在此输入图像描述

Check it out from more Java TreeSet examples .

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