Reputation: 2253
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?
Upvotes: 3
Views: 1779
Reputation: 15413
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.
Upvotes: 0
Reputation: 53694
You can use the SortedSet interface as your declaration (which has the first()
and last()
methods).
Upvotes: 2
Reputation: 40036
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<>();
Upvotes: 1
Reputation: 4262
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.
Upvotes: 5