JDK-6275004 : String and StringBuffer should be allowed in 'foreach' construct
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2005-05-24
  • Updated: 2010-05-09
  • Resolved: 2005-05-24
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
there is no reason that this shouldn't work:

  String text = "whatever"
   for (char c : text) { ... }


JUSTIFICATION :
this is exactly the reason that the 'foreach' construct was added - to simplify code where you're iterating over containers with similar values. it should be trivial to implement.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
the above syntax should work.
ACTUAL -
you need this more complex code:

  String text = "whatever"
  for (int i = 0, len = text.length(); i < len; i++) {
    char c = text.charAt(i);
    ...
  }
###@###.### 2005-05-24 05:21:23 GMT

Comments
EVALUATION To ensure correct processing, the for loop should iterate over code points, not char values. This has already been proposed as RFE 5003547. ###@###.### 2005-05-24 05:53:35 GMT ###@###.### points out that iteration over char values, as requested in the description, can be easily written as: String text = "whatever"; for (char c : text.toCharArray()) {...} Note however that iterating over char values may cause problems if supplementary characters are allowed in the string. For more information on supplementary characters and their support in the Java platform, see http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ ###@###.### 2005-05-24 23:25:24 GMT
24-05-2005