In Java 1.7.0_55, if I write this field declaration, I get a compilation error ("incompatible types"):
private final Map<String,Object> myMap =
Collections.synchronizedMap(new HashMap<>());
If I change that to read:
private final Map<String,Object> myMap =
Collections.synchronizedMap(new HashMap<String,Object>());
It compiles fine. (I'm using synchronizedMap as an example here, but the same is true for other Collections methods, unmodifiable*, synchronized*, etc)
But why does the diamond operator not work as I would expect here? Since Collections.synchronizedMap() is declared as:
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
It would seem to me that the type parameters of the constructor invocation must be the same as those of the field declaration, and the compiler should be able to infer the constructed class type parameters based on that.
I tried looking for a clause in the JLS which says this syntax is unacceptable, but I can't find one. Can anyone point me to it?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…