Enhanced For Loop

  • Recall enhanced for loop.

Here is a typical approach to step through all the elements of an array (in order):

for (int i = 0; i < myArray.length; i++) {
  System.out.println(myArray[i]);
}

There is an alternative form, the so-called enhanced for loop:

// The colon in the syntax can be read as "in"
for (int element : myArray) {
  System.out.println(element);
}

The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection (not just arrays but other data structures built into Java). It is important to note that not all data structures are "positional"; for example, there is no notion of position in a Set. So, the enhanced loop abstracts the idea of traversing the data structure elements.

In this chapter, we will provide the means to iterate (use enhanced for loop) over instances of IndexedList ADT. At the moment, one can use the "standard" for loop:

for (int i = 0; i < myIndexedList.length(); i++) {
  System.out.println(myIndexedList.get(i));
}

By the end of this chapter, we will be able to write:

// Assume myIndexedList stores elements of type Integer
for (int element : myIndexedList) {
  System.out.println(element);
}