Why doesn't my LinkedList contain an addLast () method?
I have a strange problem that I don't really understand.
I created a LinkedList like this:
List<String> customList = new LinkedList<String>();
If you type-check customList
using list instanceof LinkedList
I get true
, therefore customList is LinkedList.
Now, if I try to execute the addLast () method on customList, I get an Eclipse error:
The method addLast(String) is undefined for the type List<String>
The addList method is defined in the LinkedList class , but the only way to use this method is to declare customList as a LinkedList, not a List, thus:
LinkedList<String> customList= new LinkedList<String>();
or i need to use cast:
((LinkedList<String>) list).addLast(...);
I don't really understand this behavior, is there anyone who can give me some hint? Can you also give me a link or other link to understand this problem?
Thank you in advance
source to share
addLast
declared in the class LinkedList
, but not in the interface List
. Therefore, you can only call it using type variables LinkedList
. However, for a type variable, List
you can call add
instead as it adds an element to the end List
.
When the compiler sees a variable List
, it does not know the runtime type of the object that will be assigned to that variable. Therefore, it can let you call interface methods List
. For example, you can assign your variable to an instance ArrayList
that does not have a method addLast
, so it cannot allow you to call methods LinkedList
that are not declared in List
(or super -interface List
).
source to share