The for-each desugaring (14.14.2) looks like this:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
{VariableModifier} TargetType Identifier =
(TargetType) #i.next();
Statement
}
Here's the definition of TargetType:
"If the declared type of the local variable in the header of the enhanced for statement is a reference type, then TargetType is that declared type; otherwise, TargetType is the upper bound of the capture conversion (��5.1.10) of the type argument of I, or Object if I is raw."
The usage of 'TargetType' is confusing and incorrect:
- The type of the variable should be UnannType (or, more precisely, a new DeclaredType that accounts for array brackets), not the type of the cast. For example, a primitive variable should not be declared with a reference type.
- The cast is meant to express the implicit cast that arises due to erasure, but this is redundant: it is inherent in the use of assignment (see 5.2)
- The cast also allows a type variable with a box-type upper bound (T extends Integer) to be widened by the cast and then unboxed by the assignment. JDK-8166326 eliminates the need for a cast here.
I propose fixing the variable's declared type and getting rid of the cast entirely.