Alex Rivera | Logout

Why doesn't the diamond operator work within a addAll() call in Java 7?

Asked 2011-09-26T13:17:03.760
11

Given this example from the generics tutorial.

List<String> list = new ArrayList<>();
list.add("A");

// The following statement should fail since addAll expects
// Collection<? extends String>

list.addAll(new ArrayList<>());

Why does the last line not compile, when it seems it should compile. The first line uses a very similar construct and compiles without a problem.

Please explain elaborately.

Edit
Report

1 Answer

1

The explanation from the Type Inference documentation seems to answer this question directly ( unless I'm missing something else ).

Java SE 7 and later support limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

List<String> list = new ArrayList<>();
list.add("A");

  // The following statement should fail since addAll expects
  // Collection<? extends String>

list.addAll(new ArrayList<>());

Note that the diamond often works in method calls; however, for greater clarity, it is suggested that you use the diamond primarily to initialize a variable where it is declared.

In comparison, the following example compiles:

// The following statements compile:

List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);
answered 2011-09-26T13:48:33.400

Your Answer