Can someone explain why this code?
Collection c = (5 == 5) ? new ArrayList() : new HashSet();
produces the following compiler error:
Incompatible conditional operand types ArrayList and HashSet
For reasons that I don't understand, the following fixes the problem
Collection c = (5 == 5) ? (Collection) new ArrayList() : new HashSet();
I'm using Java 1.4.
Daniel more or less gets this right, but has deleted his answer (with five up votes).
Relevant quote from 2nd Ed JLS (1.2-1.4)
One of the types needs to be convertible to the other, which is not true of
ArrayList
andHashSet
but is true ofCollection
andHashSet
and ofArrayList
andCollection
.In 3rd Ed JLS (1.5+)
This does the obvious thing, which as it turns out is more difficult to specify and implement (I unintentionally got an early version of javac to crash on it when one of the expressions was
void
). IIRC, this was work done as part of generics.This was a bug in 1.4 and has been fixed according bugreport 5080917.