Java diamond operator does not compile
When I try to use the diamond operator like this:
List<DateTimeZone> list = new ArrayList<>();
It works great.
However, when I try to do this:
List<DateTimeZone> list = false ? null : new ArrayList<>();
It does not compile, messages: "Incompatible types: Required List found by ArrayList".
Why is this?
+3
source to share
1 answer
Ternary operator and diamond operator don't get along very well. You must explicitly specify the type:
List<Date> list = false ? null : new ArrayList<Date>();
More information on these related questions:
Impact of Java ternary operator on generics type inference
Compilation error with generics and ternary operator in JDK 7
+4
source to share