import java.util.List;
import java.util.LinkedList;
class Test {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
list.addLast("string");
list.removeLast();
}
}
When I compile the code:
$ javac Test.java
Test.java:6: error: cannot find symbol
list.addLast("string");
^
symbol: method addLast(String)
location: variable list of type List<String>
Test.java:7: error: cannot find symbol
list.removeLast();
^
symbol: method removeLast()
location: variable list of type List<String>
2 errors
If I instantiate a LinkedList with LinkedList on both sides, then there will be no errors. I have learned that putting List on the left side is better. Why did this happen?
Update #1
If the variable list
is of type List
, why does the following code print true
:
class Test {
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
System.out.println(list instanceof LinkedList);
}
}
What I interpret from the result of the above code is that list
is an instance of LinkedList
. If it's an instance of LinkedList
, why can't it call methods declared and defined in LinkedList
?
Update #2
There is forEach
method in ArrayList
but not in List
. Why am I still be able to call forEach
method on the list
variable after I do
List<String> list = new ArrayList<String>();
Does this have something to do with lambda expression?