Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6690688

Enhanced-for-loop translation as described in JLS 14.14.2 is not type-safe

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P3 P3
    • 7
    • 7
    • specification
    • 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.

            abuckley Alex Buckley
            mcimadamore Maurizio Cimadamore
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: