The For-Each Alternative to Iterators in java

If you won’t be modifying the contents of a collection or obtaining elements in reverse order, then the for-each version of the for loop is often a more convenient alternative to cycling through a collection than is using an iterator. Recall that the for can cycle through any collection of objects that implement the Iterable interface. Because all of the collection classes implement this interface, they can all be operated upon by the for.

The following example uses a for loop to sum the contents of a collection:

Use the for-each for loop to cycle through a collection

import java.util.*;

class ForEachDemo {

public static void main(String args[]) {

//Create an array list for integers. ArrayList<Integer> vals = new ArrayList<Integer>();

//Add values to the array list.






//Use for loop to display the values. System.out.print("Original contents of vals: "); for(int v : vals)

System.out.print(v + " ");

//Now, sum the values by using a for loop. int sum = 0;

for(int v : vals) sum += v;

System.out.println("Sum of values: " + sum);



The output from the program is shown here:

Original contents of vals: 1 2 3 4 5
Sum of values: 15

Leave a Comment