-2
List<List<Integer>> l = new LinkedList<LinkedList<Integer>>();
List<List<Integer>> l2 = new List<LinkedList<Integer>>();
List<List<Integer>> l3 = new LinkedList<List<Integer>();
List<List<Integer>> l4 = new LinkedList<>();

I cannot understand why only the third and the fourth statements work.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
sevenxuguang
  • 177
  • 9

1 Answers1

3

The first declaration does not work because a LinkedList<LinkedList<Integer>> is not a List<List<Integer>>. For example, by the declaration, you could add an ArrayList<Integer> to a List<List<Integer>> (a list of lists of integers). However, an ArrayList<Integer> could not be added to a LinkedList<LinkedList<Integer>> (a linked list of linked lists of integers).

The second initialization, starting with a new List could not work, as List is an interface, not a class, so it cannot be initialized with the new operator.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    @cricket_007 That's an example of an [anonymous class](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) (and not an interface). – Elliott Frisch Jan 02 '16 at 20:25