Java trernary operator

Can someone explain why this code?

Collection c = (5 == 5) ? new ArrayList() : new HashSet(); 

throws the following compiler error:

Incompatible conditional types of operands ArrayList and HashSet

For reasons that I don’t understand, the following issues are fixed.

 Collection c = (5 == 5) ? (Collection) new ArrayList() : new HashSet(); 

I am using Java 1.4.

+4
source share
2 answers

This was a bug in 1.4 and was fixed according to bugreport 5080917 .

Rating This is a mistake.

xxxxx @xxxxx 2004-07-30

+7
source

Daniel more or less correctly understands this, but deleted his answer (with five votes).

Corresponding quote from the second Ed JLS (1.2-1.4)

  • If the second and third operands are of different reference types, then it should be possible to convert one of the types to another type (calling this last type T) by assigning the conversion (§5.2); type conditional expression T. This is a compile-time error if none of them is compatible with another type.

One of the types must be converted to another, which is not true for ArrayList and HashSet , but true for Collection and HashSet and ArrayList and Collection .

In the third Ed JLS (1.5 +)

  • Otherwise, the second and third operands are of types S1 and S2, respectively. Let T1 be the type that results from applying boxing transforms to S1, and T2 is the type obtained by applying boxing transforms to S2. A conditional expression type is the result of applying the capture transform (Section 5.1.10) to lub (T1, T2) (§15.12.2.7).

This does the obvious thing, which turned out to be harder to point out and implement (I accidentally accidentally got an early version of javac so that it crashes when one of the expressions was void ). IIRC, it was a job done as part of a generic drug.

+3
source

Source: https://habr.com/ru/post/1314756/


All Articles