Re: Improved for each loop
Roedy Green wrote:
You might generalise that to also permit things like this:
for ( int i: anArray )
for ( int i: anArrayList )
for ( int i: someString )
I think those extensions are safe. If muddled them up with the
existing forms, the body of the loop would generate type errors.
Daniel Pitts wrote:
Not really:
int[] anArray;
for (int i: anArray) // Oops.
List<Integer> anArrayList;
for (int i: anArrayList) // oops.
I guess by "oops" you mean that the syntax is already valid in current Java.
I had a hard time seeing that as "oops", more like "huzzah".
<sscce>
package testit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public final class LoopGuru
{
public static void main( String [] args )
{
final Random ran = new Random();
int [] primitivos =
{ ran.nextInt(), ran.nextInt(), ran.nextInt(),
ran.nextInt(), ran.nextInt(), ran.nextInt(),
};
List <Integer> instances =
new ArrayList <Integer> (primitivos.length);
System.out.println( "array" );
System.out.print( "{ " );
for ( int ix : primitivos )
{
System.out.print( ix );
System.out.print( ", " );
instances.add( Integer.valueOf( ix ));
}
System.out.println( "}" );
System.out.println( "list" );
System.out.print( "{ " );
for ( int ix : instances )
{
System.out.print( ix );
System.out.print( ", " );
}
System.out.println( "}" );
}
}
</sscce>
Output:
array
{ 627089629, 1671919000, -211269067, -241006977, 1094855336, 1531172813, }
list
{ 627089629, 1671919000, -211269067, -241006977, 1094855336, 1531172813, }
--
Lew