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 >();

	public static void main( String[] args )
	{
		DvdTitle              title  = null;
		ArrayList< DvdTitle >	titles = new ArrayList< DvdTitle >();

		DvdCreateTestTitles.main( null );

		for( String	aTitle : DvdCreateTestTitles.titlenames )
		{
			try
			{
				title = loadTitleFromFile( aTitle );
			}
			catch( FileNotFoundException e )
			{
				log.error( "Failed to find "
				           + aTitle
				           + "\n"
				           + e.getMessage() );
			}
			catch( IOException e )
			{
				log.error( "IOException occurred loading from "
				           + aTitle
				           + "\n"
				           + e.getMessage() );
			}
			.
			.
			.
			titles.add( title );
			.
			.
			.
		}

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

	public static void main( String[] args )
	{
		ArrayList< DvdTitle >	titles = new ArrayList< DvdTitle >();

		DvdCreateTestTitles.main( null );

		for( int i = 0; i < DvdCreateTestTitles.titlenames.size(); i++ )
		{
			String	aTitle = DvdCreateTestTitles.titlenames.get( i );
			.
			.
			.
		}

—more elegant, I think.