The new for loop uses the enhanced features of JDK 1.5 and uses the inbuilt iterator feature of collections and uses them to iterate through values in a collection in a easier manner
package test;
import java.util.ArrayList;
import java.util.Iterator;
import test.Group.Element;
public class TestEnhancedForLoop implements Iterable<TestEnhancedForLoop.Element>{
static class Element {
String name;
Element(String name) {
this.name = name;
}
public String toString() {
return "Element{" + name + "}";
}
}
static ArrayList lst = new ArrayList();
/**
* @param args
*/
public static void main(String[] args) {
TestEnhancedForLoop obj = new TestEnhancedForLoop();
obj.addElement(new Element("Element One"));
obj.addElement(new Element("Element Two"));
obj.addElement(new Element("Element Three"));
for (Element p : obj) {
System.out.println(p);
}
}
public void addElement(Element p) {
lst.add(p);
}
public Iterator iterator() {
return getElements();
}
private Iterator getElements() {
return lst.iterator();
}
}