TreeSet in Java

Viewed 1314

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?

4 Answers

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.

enter image description here

Check it out from more Java TreeSet examples.

Related