This is the second tutorial on the enhanced for loop on collections. Earlier one is with arrays – Arrays Enhanced for loop (foreach).
Collections Enhanced new for loop
Observe the following program.
import java.util.ArrayList;
public class ForEachCollections
{
public static void main(String args[])
{ // enhanced for loop with generics Integer array list
ArrayList al1 = new ArrayList();
al1.add(100);
al1.add(200);
al1.add(300);
System.out.print("Printing int array list with taditional for loop: ");
for(int i = 0 ; i < al1.size(); i++)
{
System.out.print(al1.get(i) + " ");
}
System.out.print("\nPrinting int array list with enhanced for loop: ");
for(int k : al1)
{
System.out.print(k + " " );
}
// enhanced for loop with generics String array list
ArrayList al2 = new ArrayList();
al2.add("Sridhar");
al2.add("Jyothi");
al2.add("Jyothna");
System.out.print("\n\nPrinting string array list with taditional for loop: ");
for(int i = 0 ; i < al2.size(); i++)
{
System.out.print(al2.get(i) + " ");
}
System.out.print("\nPrinting string array list with enhanced for loop: ");
for(String str : al2)
{
System.out.print(str + " " );
}
}
}
A generic ArrayList al1 that stores int values and al2 storing string values are created and elements are added.
for(int k : al1)
{
System.out.print(k + " " );
}
Make a note, the data type stored by array list and the variable in the for loop are the same.
Collections Enhanced new for loop with Objects
Generics store only one type of data like all integers or all doubles or all Student objects etc. To store all types of objects like integers, doubles, Dates, Employees, a generic type Object can be taken as every object can be converted into the super-most class object Object.
To store any object, the loop can be modified as follows.
import java.util.*;
public class Demo
{
public static void main(String args[])
{
ArrayList