Showing posts with label forEach. Show all posts
Showing posts with label forEach. Show all posts

Wednesday, May 18, 2011

Iterating over 2 Dimensional Arrays

Iterating down rows, then across columns is often better. The most common practice is for the outer loop be for the row and the inner loop for the column. If your program requires the outer iteration by columns, that's fine, but the default row-first iteration gives the best performance because "locality of reference" improves the perfomance of cache and virtual memory. It also allows use of the handy foreach loop.

int[][] a2 = new int[ROWS][COLS];

String output = ""; // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
output += " " + a2[row][col];
}
output += "\n";
}


foreach style for loop


for (int[] row : a2) {
for (int val : row) {
output += " " + val;
}
output += "\n";
}

Tuesday, May 17, 2011

Iterating over an array in java

Java provides 2 ways of iterating over arrays.

Traditional or old style iteration

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



New style


JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.


for (variable : collection)
statement

sets the given variable to each element of the collection and then executes the statement (which, of course, may be a block). The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList For example,



for (int element : a)
System.out.println(element);

So here we are taking element from array a and dumping it on output.


Note: println prints each element of the array a on a separate line.


You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).


"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.


Chitika