0

what this code means. why List = LinkedList

List<String> list1 = new LinkedList<String>();
List<String> list2 = new LinkedList<String>();
  • It a casting approach. List is more generic than LinkedList. WHen using this in parameters or variables, you can now assign/pass anything derived from List into it. (LinkedList, but also DoubleLinkedList, ...List, etc.) – Marvin Smit Aug 30 '14 at 10:25
  • For now I am voting to close your question as duplicate. If you don't agree with my action feel free to inform me about it and include reason why it is not duplicate. In that case you should also [edit] your question with more details about informations you want to know, which are not included in duplicate question. – Pshemo Aug 30 '14 at 10:54

2 Answers2

1

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.

Community
  • 1
  • 1
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
0

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138