You can iterate over arrays either by using enhanced for loop (aka foreach) or by using array indices:
int[] array = new int[10];
// 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 = {1, 2, 3};
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 = {1, 2, 3};
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[][] array = new int[10][10];
for (int indexOuter = 0; indexOuter < array.length; indexOuter++) {
for (int indexInner = 0; indexInner < array[indexOuter].length; indexInner++) {
array[indexOuter][indexInner] = indexOuter + indexInner;
}
}
for (int[] numbers : array) {
for (int value : numbers) {
System.out.println(value);
}
}
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: