ArrayLists


For Each Loop

If we are not adding or deleting items in an ArrayList, we can use the special for each style of loop to step through the list.

    // Print every number in an ArrayList<Integer>.
    for ( Integer value : numberList )
        System.out.println(value);

    // Ask every fish in an ArrayList<AquaFish> to move forward.
    for ( AquaFish f : fishList )
        f.moveForward();

The latter is equivalent to:

    // Ask every fish in an ArrayList<AquaFish> to move forward.
    for ( int i = 0; i < fishList.size(); i++ )
    {
        AquaFish f = fishList.get(i);
        f.moveForward();
    }

Alyce Brady, Kalamazoo College