Java 10: Will Java 7's Diamond Inference Work with Local Type Inference?

Jacob G. :

From JEP 286, we see that we'll be able to utilize local type inference (var) in JDK 10 (18.3). The JEP states that the following compiles, which is expected:

var list = new ArrayList<String>();  // infers ArrayList<String>

I'm curious to know what would happen if we attempt the following:

var list = new ArrayList<>();

Will what I proposed in the second snippet even compile? If so (which I doubt), would the ArrayList accept Object as its generic type?

I'd try this myself, but I don't have access to any machines which I can install early releases on.

Thanks!

ZhekaKozlov :

Yes, var and the diamond operator can be combined together. The compiler will infer the most specific generic type:

var list = new ArrayList<>(); // Infers ArrayList<Object>
var list = new ArrayList<>(List.of(1, 2, 3)); // Infers ArrayList<Integer>

And you can even combine them with an anonymous class:

var list = new ArrayList<>() {};

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=425300&siteId=1