Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeSet in Java

Tags:

java

set

treeset

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?

like image 369
Zeus Avatar asked Apr 13 '26 10:04

Zeus


1 Answers

Thelast() 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.

like image 196
Mapsy Avatar answered Apr 16 '26 00:04

Mapsy