I have a strange problem I really can't understand.
I've created a LinkedList in this way:
List<String> customList = new LinkedList<String>();
If check the type of customList
using list instanceof LinkedList
i get true
, so customList is a LinkedList.
Now, if I try to execute the method addLast() on customList i get an Eclipse error:
The method addLast(String) is undefined for the type List<String>
The method addList is defined in the class LinkedList but the only way to use this method is to declare customList as a LinkedList and not as a List, in this way:
LinkedList<String> customList= new LinkedList<String>();
or I have to use a cast:
((LinkedList<String>) list).addLast(...);
I really don't understand this kind of behaviour, is there someone who can give me some hint? Can you also give me some link or other reference in order to understand this problem?
Thanks in advance
addLast
is declared in the LinkedList
class, but not in the List
interface. Therefore you can only call it using variables of LinkedList
type. However, for a variable of List
type you can call add
instead, since it adds the element to the end of the List
.
When the compiler sees a List
variable, it doesn't know the runtime type of the object that would be assigned to that variable. Therefore it can only let you call methods of the List
interface. For example, you might assign to your variable an ArrayList
instance which doesn't have an addLast
method, so it can't let you call methods of LinkedList
that are not declared in List
(or a super-interface of List
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With