Possible Duplicate:
Double brace initialisation (anonymous inner class) with diamond operator
Using Java 7, why is the following a problem
final List<String> a = new ArrayList<>() {
{
add("word");
}
};
Explicit type declaration is needed as in
final List<String> a = new ArrayList<String>() {
{
add("word");
}
};
IMHO, In general, Java avoids type inference.
In any case, the
<>only works when the compiler doesn’t need to know which generic type was used. In the case of the anonymous classes, the actual type needs to be provided as the compiler doesn’t infer the type.Effectively
<>turns off the type checking, rather than providing type inference. An anonymous class stores the actual generic type and so you have to provide it.is rather like
but for an anonymous subclass the compiler needs to give it a generic type.