-
Enhancement
-
Resolution: Fixed
-
P3
-
7
-
None
-
rc
-
x86
-
linux_ubuntu
-
Verified
JLS 14.14.2 says that, given an enhanced-for-loop statement in the form:
EnhancedForStatement:
for ( VariableModifiersopt Type Identifier: Expression) Statement
This should be translated by the compiler as follows:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt Type Identifier = #i.next();
Statement
}
However, because of type-erasure, the proposed translation is not type-safe. In fact, given the fact that the runtime type-signature for Iterator.next() is ()Ljava/lang/Object; javac should also emit a cast in order to preserve type-safety: the translation should thus look as follows:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt VarType Identifier = (TargetType)#i.next();
Statement
}
Where TargetType has to be carefully chosen among the existing possibilities:
1) The type of the enhanced-for-loop variable (VarType)
2) The type of the parameter of the Iterable class that has to be iterated
Currently javac applies 2), but this is source of some problems as described in the related CR 6500701.
Translation for enhanced-for-loop exploiting arrays should be adjusted as well.
EnhancedForStatement:
for ( VariableModifiersopt Type Identifier: Expression) Statement
This should be translated by the compiler as follows:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt Type Identifier = #i.next();
Statement
}
However, because of type-erasure, the proposed translation is not type-safe. In fact, given the fact that the runtime type-signature for Iterator.next() is ()Ljava/lang/Object; javac should also emit a cast in order to preserve type-safety: the translation should thus look as follows:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt VarType Identifier = (TargetType)#i.next();
Statement
}
Where TargetType has to be carefully chosen among the existing possibilities:
1) The type of the enhanced-for-loop variable (VarType)
2) The type of the parameter of the Iterable class that has to be iterated
Currently javac applies 2), but this is source of some problems as described in the related CR 6500701.
Translation for enhanced-for-loop exploiting arrays should be adjusted as well.
- relates to
-
JDK-6500701 Enhanced for loop with generics generates faulty bytecode
-
- Closed
-
-
JDK-6923689 Enhanced for loop with unsafe generics is incorrectly desugared.
-
- Closed
-
-
JDK-6923696 Allow mixed array brackets for enhanced for loop's variable
-
- Closed
-
-
JDK-8166421 14.14.2: Bugs in desugaring of for-each
-
- Open
-