Posts Tagged: java for each


29
Feb 08

New jdk 1.5 ‘for’ loop ( Enhanced for loop-’for each’)

int a[] = {1,2,3,4,5};

for(int i =0;i<a.length;i++)

{

System.out.println(“Value: “+a[i]);

}

This is so 1.4!!!

Here’s how you do it with the new and enhanced for loop :

for(int b: a)

{

System.out.println(“Value :”+b);

}

To make it easy for you to understand how to interpret the above condition, read it as follows:

” for each int b in a…..iterate”

Basically what you have to do is – To the left of the colon in the for loop declare the datatype that is present inside the array and to the right of the colon write the name of the array.

The above ‘for’ loop will iterate as many times as there are elements in the array ‘a’. At every iteration int b will have the value of the next element.

In simple terms its like this:

for(int b: a) will internally expand like this : for(int i=0;i<a.length;i++){int b=a[i];}

You can use this for loop for iterating over type collections too.

Example :

List<MyObject> al = new ArrayList();

//Create an Object of some class you want to put into the arraylist.

MyObject myObject = new MyObject();

MyObject myObject1 = new MyObject();

al.add(myObject);

al.add(myObject1);

for(MyObject o : al)

{

System.out.println(“Object hashcode is “+o.hashCode());

}