Iterating over arrays


You can iterate over arrays either by using enhanced for loop (aka foreach) or by using array indices:

// using indices: read and write
for (int i = 0; i < array.length; i++)
{
    array[i] = i;
}
 
// extended for: read only
for (int e : array)
{
    System.out.println(e);
}

It is worth noting here that there is no direct way to use an Iterator on an Array, but through the Arrays library it can be easily converted to a list to obtain an Iterable object.

For boxed arrays use Arrays.asList:

Integer[] boxed = {10, 20, 30};
Iterable<Integer> boxedIt = Arrays.asList(boxed); // list-backed iterable
Iterator<Integer> fromBoxed1 = boxedIt.iterator();

For primitive arrays (using java 8) use streams (specifically in this example - Arrays.stream -> IntStream):

int[] primitives = {10, 20, 30};
IntStream primitiveStream = Arrays.stream(primitives); // list-backed iterable
PrimitiveIterator.OfInt fromPrimitive1 = primitiveStream.iterator();

If you can't use streams (no java 8), you can choose to use google's guava library:

Iterable<Integer> fromPrimitive2 = Ints.asList(primitives);

In two-dimensional arrays or more, both techniques can be used in a slightly more complex fashion.

Example:

int[][] matrix = new int[5][5];
for (int outerIndex = 0; outerIndex < matrix.length; outerIndex++) {
    for (int innerIndex = 0; innerIndex < matrix[outerIndex].length; innerIndex++) {
        matrix[outerIndex][innerIndex] = outerIndex * innerIndex;
    }
}
 
// Enhanced for loop to print the values
for (int[] row : matrix) {
    for (int element : row) {
        System.out.println(element);
    }
}

It is impossible to set an Array to any non-uniform value without using an index based loop.

Of course you can also use while or do-while loops when iterating using indices.

One note of caution: when using array indices, make sure the index is between 0 and array.length - 1 (both inclusive). Don't make hard coded assumptions on the array length otherwise you might break your code if the array length changes but your hard coded values don't.

Example:

int[] values = {5, 10, 15, 20, 25};
public void incrementValues() {
    // DO THIS:
    for (int i = 0; i < values.length; i++) {
        values[i] += 5; // or values[i] = values[i] + 5; or values[i]++;
    }
    // DON'T DO THIS:
    for (int i = 0; i < 3; i++) {
        values[i] += 5;
    }
}

It's also best if you don't use fancy calculations to get the index but use the index to iterate and if you need different values calculate those.

Example:

public void fillArrayWithDoubleIndex(int[] numbers) {
    // DO THIS:
    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = i * 3;
    }
    // DON'T DO THIS:
    int doubleLength = numbers.length * 3;
    for (int i = 0; i < doubleLength; i += 3) {
        numbers[i / 3] = i;
    }
}

Accessing Arrays in reverse order

int[] array = {0, 1, 1, 2, 3, 5, 8, 13};
for (int i = array.length - 1; i >= 0; i--)
{
    System.out.println(array[i]);
}
 

Using temporary Arrays to reduce code repetition

Iterating over a temporary array instead of repeating code can make your code cleaner. It can be used where the same operation is performed on multiple variables

String itemName = "Cassandra";
int unitCount = 20;
double weight = 36.8;
int wheels = 6;
int doors = 4;
 
// Copy-paste approach:
System.out.println(itemName);
System.out.println(unitCount);
System.out.println(weight);
System.out.println(wheels);
System.out.println(doors);
 
// Temporary array approach:
for (Object attribute : new Object[]{itemName, unitCount, weight, wheels, doors})
    System.out.println(attribute);
 
// Using only numbers for square root:
for (double number : new double[]{unitCount, doors, weight})
    System.out.println(Math.sqrt(number));

Keep in mind that this code should not be used in performance-critical sections, as an array is created every time the loop is entered, and that primitive variables will be copied into the array and thus cannot be modified.

Basic Programs