what this code means. why List = LinkedList
List<String> list1 = new LinkedList<String>();
List<String> list2 = new LinkedList<String>();
what this code means. why List = LinkedList
List<String> list1 = new LinkedList<String>();
List<String> list2 = new LinkedList<String>();
Because List
is an interface, which may be assigned to any implementing classes. LinkedList
implements List
, therefore the assignment is legal. See programming to an interface.
You see a design feature of the language.
List is a general API which is distinghuished from other types by
public interface List<T> ...
public int size();
public T get(int i);
where as the implementing classes are specified as such:
public class LinkedList implements List ...
publlc class ArrrayList implements List ...
By declaring a variable to be of that "interface" you leave the implementation open (for instance to change in the future, or reassign with another object). You do not overspecify the variable).
This also allows to have functions handling any kind of List.
void f(List list) { ... }
Some other, simpler languages do not have this choice and have one kind of List, one kind of Map, one kind of Set. By allowing the programmer the choice of implementation a technical quality is given. Like choosing a car brand instead of Car.