Page 1 of 1

The For-each Loop Rate Topic: ***** 1 Votes

#1 anonymouscodder  Icon User is offline

  • member icon

Reputation: 126
  • View blog
  • Posts: 710
  • Joined: 01-January 10

Posted 03 January 2010 - 04:41 PM

The For-each Loop


What is the For-each loop?
The For-each loop was introduced in Java 5 offering a way to iterate arrays and collections in a more comfortable manner. It's also know as foreach, enhanced for and for-in loop.

When should I use it?
Any time you can, because it clarifies your code.

Important note:
The For-each loop is not a way to substitute the for loop, it's a way to iterate over arrays and collections.
The For-each loop it's supported only by Java 5 or older. If you want compatibility with older versions you should not use it.

How the For-each loop looks like?
Iterating an array using a for loop:
For loop example[/b]]int getSum(int[] array) {
    int sum = 0;
    for(int i = 0; i < array.length; ++i) {
        sum += array[i];
    }
    return sum;
}


Iterating an array using a for-each loop:
For-each loop example[/b]]int getSum(int[] array) {
    int sum = 0;
    for(int value : array) {
        sum += value;
    }
    return sum;
}


Iterating a collection using a while loop and a Iterator:
While loop with a Iterator example[/b]]int getSum(Collection<Integer> collection) {
    int sum = 0;
    Iterator<Integer> iterator = collection.iterator();
    while(iterator.hasNext()) {
        sum += iterator.next().intValue();
    }
    return sum;
}


Iterating a collection using a for-each loop:
For-each loop example[/b]]int getSum(Collection<Integer> collection) {
    int sum = 0;
    for(Integer value : collection) {
        sum += value.intValue();
    }
    return sum;
}


How do I make my class work with the for-each loop?
Your class must implement the Iterable interface. Let's suppose you have the following classes:

Card class[/b]]public class Card {
    //Class implementation (irrelevant)
}

Deck class[/b]]public class Deck {
    private ArrayList<Card> cards;
    //Another fields and methods (irrelevant)
}

Deck represents a collection of cards, but you can't use it with a for-each loop.

The following (re)implementation is compatible with the for-each loop:
Deck class with Iterable interface implemented[/b]]public class Deck implements Iterable<Card> {
    private ArrayList<Card> cards;
    public Iterator<Card> iterator() {
        return cards.iterator();
    }
    //Another fields and methods (irrelevant)
}

The Deck class holds a ArrayList collection, that have a iterator() method. That makes the job easier, but of course you can return your own iterator.

Final considerations:
The classes and interfaces ArrayList, Collection, Iterable, Iterator are located in the java.util package.
The Integer class is located in java.lang package.
The for-each loop is supported only by Java 5 or older.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1