Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my LinkedList doesn't contains addLast() method?

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

like image 482
Ema.jar Avatar asked Jan 08 '23 22:01

Ema.jar


1 Answers

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

like image 120
Eran Avatar answered Jan 10 '23 10:01

Eran