On Java7 diamond refinement needed

Possible duplicate:
Double brace initialization (anonymous inner class) with diamond operator

Using Java 7, why the following problem occurs:

final List<String> a = new ArrayList<>() { { add("word"); } }; 

An explicit type declaration is required, as in

 final List<String> a = new ArrayList<String>() { { add("word"); } }; 
+4
source share
2 answers

IMHO, In general, Java avoids type inference.

In any case, <> only works when the compiler does not need to know which generic type was used. In the case of anonymous classes, the actual type must be provided, since the compiler does not infer the type.

Effectively <> disables type checking, and does not provide type inference. An anonymous class stores the actual generic type and therefore you must provide it.

 List<String> a = new ArrayList<>() 

rather like

 @SuppressWarnings("unchecked") List<String> a = new ArrayList() 

but for an anonymous subclass, the compiler must give it a generic type.

+4
source

Diamond for anonymous class is not supported due to some technical support

Compilation error: "<> cannot be used with anonymous classes

+2
source

Source: https://habr.com/ru/post/1439426/


All Articles