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.


No comments:

Post a Comment

Chitika