3

When I try to use the diamond operator as follows:

List<DateTimeZone> list = new ArrayList<>();

It works perfectly.

However, when I try this:

List<DateTimeZone> list = false ? null : new ArrayList<>();

It doesn't compile, messaging: "Incompatible types: required List, found ArrayList".

Why is that?

user1028741
  • 2,745
  • 6
  • 34
  • 68

1 Answers1

4

The ternary operator and the diamond operator don't get along very well. You have to specify the type explicitly:

List<Date> list = false ? null : new ArrayList<Date>();

More info at these related questions:

Java ternary operator influence on generics type inference

Compilation error with generics and ternary operator in JDK 7

Community
  • 1
  • 1
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107