Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

generics - Why does the diamond operator not work for java.util.Collections methods in Java 7?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This fails with your compiler error in Java 7, but it compiles successfully in Java 8. In short, the compiler's type inference did not catch the proper inferred types in Java 7, but the better type inference infers the proper types in Java 8.

This change was JEP (JDK Enhancement Proposal) 101 for Java 8.

Summary

Smoothly expand the scope of method type-inference to support (i) inference in method context and (ii) inference in chained calls.

Java 8 is able to infer types through multiple method calls with parameters and method call chaining. It can now determine from the left side of the assignment <String, Object> through the call to Collections.synchronizedMap to the diamond operator in the parameter to that call, new HashMap<>().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...