Ad

Saturday 3 October 2009

Enhanced for loop in Java 5(To iterate the Collection objects)

Prior to version java 5 ,we can use only the Iterator interface to iterate the collections .The below code sample show us the typical use of iterator interface.

List strlist = new ArrayList();
strlist.add("one");
strlist.add("two");
strlist.add("three");
Iterator it=strlist.iterator();
while(it.hasNext())
{
System.out.println("String in Collections---"+it.next());                                                                          
}


Output:
String in Collections---one
String in Collections---two
String in Collections---three

But from version java 5,we can use the Enhanced for loops to iterate the collections instead of using iterator interface.Enhanced for loops will make the code looks easier and simpler as shown below


List<String> strlist = new ArrayList<String>();                                                                                        
strlist.add("one");
strlist.add("two");
strlist.add("three");
for(String str:strlist)
{
System.out.println("String in Collections---"+str);
}


Output:
String in Collections---one
String in Collections---two
String in Collections---three

No comments:

Post a Comment