Home | FAQ | Contact me

The new for loop in Java 5

Along with generics and enumerations, Java 5 acquired a new for loop befitting (especially) the new generics stuff. It's a kind of foreach construct you've seen in other languages such as bash. Here I give a rather good example.

Inside this code

In terms of beginning Java samples you have:

In the example below, DvdCreateTestTitles.main() creates 4 serializations of objects of type DvdTitle for test purposes within a larger application. Inside DvdCreateTestTitles.java, titlenames is defined:

public static ArrayList< String > titlenames = new ArrayList< String >();

01.public static void main( String[] args )
02.{
03.  DvdTitle              title  = null;
04.  ArrayList< DvdTitle >  titles = new ArrayList<>();
05. 
06.  DvdCreateTestTitles.main( null );
07. 
08.  for( String  aTitle : DvdCreateTestTitles.titlenames )
09.  {
10.    try
11.    {
12.      title = loadTitleFromFile( aTitle );
13.    }
14.    catch( FileNotFoundException e )
15.    {
16.      log.error( "Failed to find "
17.                 + aTitle
18.                 + "\n"
19.                 + e.getMessage() );
20.    }
21.    catch( IOException e )
22.    {
23.      log.error( "IOException occurred loading from "
24.                 + aTitle
25.                 + "\n"
26.                 + e.getMessage() );
27.    }
28.    .
29.    .
30.    .
31.    titles.add( title );
32.    .
33.    .
34.    .
35.  }

This is the same as we used to do like this:

01.public static void main( String[] args )
02.{
03.  ArrayList< DvdTitle > titles = new ArrayList< DvdTitle >();
04. 
05.  DvdCreateTestTitles.main( null );
06. 
07.  for( int i = 0; i < DvdCreateTestTitles.titlenames.size(); i++ )
08.  {
09.    String  aTitle = DvdCreateTestTitles.titlenames.get( i );
10.    .
11.    .
12.    .
13.  }

—more elegant, I think.