JDK-6360734 : Enhanced for loop should support iterators directly
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 5.0,6
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: linux,windows_xp
  • CPU: x86
  • Submitted: 2005-12-08
  • Updated: 2010-04-04
  • Resolved: 2006-11-02
Related Reports
Duplicate :  
The enhanced for loop introduced in Java 5 requires that the object being looped over be either an array, or a class that implements Iterable.  It should also permit an Iterator to be used directly.  For example, the following code should be legal:

for (ImageReader reader : ImageIO.getImageReaders(stream))
  // do something with it

Currently, the compiler produces the error message, "foreach not applicable to expression type."

There are many classes that provide access to data by means of Iterators, but do not actually implement the Iterable interface.  In some cases, this is simply because they were created prior to Java 5.  In other cases, the Iterable interface is  inappropriate, such as the example above where a class has several methods that each return a different Iterator.  It should still be possible to use the enhanced for loop in these cases.