Java 5 for loop syntax example (Java 5 Generics)

Java FAQ: Can you show me an example of the Java 5 for loop syntax? (Java 5 and newer)

Answer: Sure. I’ve created a sample Java program to demonstrate the Java 5 for-each loop syntax, using both a List with pre-Java5 syntax, and a second example using Java 5 generics syntax.

Java 5 for loop syntax example

Without any further ado, here’s the example code:

package com.alvinalexander.javasamples;

import java.util.ArrayList;
import java.util.List;

public class Java5ForLoopExample
{

  public static void main(String[] args)
  {
    exampleWithoutJava5Generics();
    exampleWithJava5Generics();
  }

  private static void exampleWithoutJava5Generics()
  {
    List integers = new ArrayList();
    integers.add(new Integer(1));
    integers.add(new Integer(2));
    integers.add(new Integer(3));

    // you get an Object back from a List
    for (Object integer : integers)
    {
      // don't have to use toString(); but you might need
      // to convert from an Object to an Integer in a more
      // complicated example
      System.out.println(integer.toString());
    }
  }

  private static void exampleWithJava5Generics()
  {
    List integers = new ArrayList();
    integers.add(new Integer(4));
    integers.add(new Integer(5));
    integers.add(new Integer(6));

    // you get an Object back from a List
    for (Integer integer : integers)
    {
      // here you know for sure that you're dealing with
      // an Integer reference
      System.out.println(integer);
    }
  }
}

As you can see from the sample code, the exampleWithoutJava5Generics method shows how to use the for loop syntax with a list that doesn’t specify the object type being held by the List. In this example method when you get the items out of the list you get them out as Objects, which you must then cast to the correct type.

In the second example, the exampleWithJava5Generics method shows how to use the new for loop syntax with a Generics collection, where you did specify the type of the collection when you created it. In this cast the extra casting step is not required, and in my example I can just treat the reference from the list as an Integer.

(Yes, I know, this example would have been better if I needed to call a method on the reference that I pulled from the list that was specific to the Integer class, but alas, I am out of time for today.)