skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Friday, October 5, 2012

Java - Enhanced For Loop for JDK 1.5

Posted by Raju Gupta at 11:37 PM – 0 comments
 
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();
 }

}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger