For loop in jdk 5
Let us see how for loop has chnaged from JSK 1.4 to jdk 1.5
We create a List
List countryList=new ArrayList();
countryList.add(“India”);
countryList.add(“USA”);
countryList.add(“Russia”);
countryList.add(“Brazil”);
countryList.add(“China”);The for loop
for (Iterator countryIter=countryList.iterator(); countryIter.hasNext();) {
System.out.println(“Inside forLoop_1_JDK4 “+countryIter.next());
}
}
In JDK 5 , the for loop could be written as
List<String> countryList=new ArrayList<String>();
countryList.add(“India”);
countryList.add(“USA”);
countryList.add(“Russia”);
countryList.add(“Brazil”);
countryList.add(“China”);for (String country : countryList) {
System.out.println(“Inside forLoop_in JDK 5 “+country);
}
}
This is the use of generics in
List<String> countryList=new ArrayList<String>();
This tells the compiler that it is a list of type String.
Understanding the for loop
for (String str : countryList) {
In this statement first parameter must be a Java type that corresponds to the generic type specified when the collection was created.
The next parameter would be the name of this access variable. This name would be used within the loop
The last parameter is the name of the collection which is to be iterated over.
What is the advantage of this new for loop ?
Since the compiler already knew that it was of type String, there was no need to explicitly parse it.
Important:
1. for enhanced for loop to work , the generic type of the object has to be defined.
2. If you add any object of any other type for eg Int or StringBuffer, you would get a compile time error.
List countryList=new ArrayList();
countryList.add(“India”);
countryList.add(“USA”);
countryList.add(“Russia”);
countryList.add(“Brazil”);
countryList.add(“China”);
for (Iterator countryIter=countryList.iterator();countryIter.hasNext();) {
System.out.println(“Inside forLoop_1_JDK4 “+countryIter.next());
}
}








