Step through a Collection in Java Code - dummies

By Barry Burd

Some Java programs used in Android apps use a for loop with indexes to step through a collection. The code does what it’s supposed to do, but it’s a bit awkward. When you’re piling objects into a collection, you shouldn’t have to worry about which object is first in the collection, which is second, and which is third, for example.

Java has two features that make it easier to step through a collection of objects. One feature is the iterator. This listing shows you how an iterator works.

package com.allmycode.collections;
import java.util.ArrayList;
import java.util.Iterator;
public class SimpleCollectionsDemo {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("Hello");
    arrayList.add(", ");
    arrayList.add("readers");
    arrayList.add("!");
    Iterator<String> iterator = arrayList.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next());
    }
  }
}

The output from running the listing is shown in the figure.

image0.jpg

When you have a collection (such as an ArrayList), you can create an iterator to go along with that collection. In the listing, you are shown how to create an iterator to go along with the arrayList collection, by calling

 Iterator<String> iterator = arrayList.iterator();

After you’ve made this call, the variable iterator refers to something that can step through all values in the arrayList collection. Then, to step from one value to the next, you call iterator.next() repeatedly.

And, to find out whether another iterator.next() call will yield results, you call iterator.hasNext(). The call to iterator.hasNext() returns a boolean value: true when there are more values in the collection and false when you’ve already stepped through all the values in the collection.

An even nicer way to step through a collection is with Java’s enhanced for statement. This listing shows you how to use it.

package com.allmycode.collections;
import java.util.ArrayList;
public class SimpleCollectionsDemo {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("Hello");
    arrayList.add(", ");
    arrayList.add("readers");
    arrayList.add("!");
    for (String string : arrayList) {
      System.out.print(string);
    }
  }
}

An enhanced for statement doesn’t have a counter. Instead, the statement has the format shown in the figure.

for statement.”/>
The anatomy of an enhanced for statement.

The enhanced for statement in the listing achieves the same effect as the iterator and the ordinary for statement. That is, the enhanced for statement steps through the values stored in the arrayList collection.

The enhanced for statement was introduced in Java 5.0. It’s “enhanced” because, for stepping through a collection, it’s easier to use than a pre-Java 5.0 for statement.