Java foreach

Iterating over a collection of objects and performing some action on each object is one of the most common task while programming .

Java foreach

Java foreach

     

 

Iterating over a collection of objects and performing some action on each object is one of the most common task while programming. There are many different iteration techniques that requires to type a good amount of characters and thus costs you more time. Java 1.5 provides many new features including a new way of iterating over a collection of elements. This new feature is known as for-each loop that can be considered as enhanced for loop. This new syntactical construct has been designed to simplify iteration over a collection of elements. For-each construct is used with generics elegantly that takes care of type safety also.

The syntax of for-each loop is shown here:

for(type vaiable : collection){ Statements; } 

and

for (type vaiable: array) { Statements; }

Effective use of the foreach loop depends on parameterized types that you are using. Here is the example that shows the element of the List?s object.

 

List names = new ArrayList();
names.add("a");
names.add("b");
names.add("c");

for (Iterator it = names.iterator(); it.hasNext(); ) {   String name = (String)it.next();   System.out.println(name.charAt(0));

 


Another example shows the for-each loop using the Array?s object.

 

int[] a={1,2,3,4,5,6,7,8,9,0};
  for(int i : a){
  System.out.println(i);
  }

 


Read more at:

http:/www.roseindia.net/java/java-tips/flow/loops/foreach.shtml