FOR-EACH Loop

Add to Technorati Favorites
Java 5 introduced a lot of new features which were being sought for quite long. It is a total overhaul of the language. Though these features have minimum or no effect on produced bytecode, Bytecode remains unchanged.

FOR-EACH LOOP:

It is irritating. I need to traverse all elements in a data structure and for this I have to write a conditional loop as I do in C language. Come on, it is a high level language, it should have natural processing. Most natural way should be,

"FOR EACH ELEMENT IN DATA STRUCTURE, DO SOMETHING"

And it is what, the Sun engineers did. They introduced a "FOR EACH" loop for traversing all the elements in a data structure but with a condition, data structure should implement "Iterable" interface.

PS : There is one exception to it. Arrays can also be iterated in this way.

Syntax for "FOR EACH" loop is:

For(Element e : DATA STRUCTURE (of type element) ){

//do something with e

}


Let's illustrate it with some examples.

Let's define a Java Collection and traverse it. All collections in Java are of type Collection and Collection Interface (java.util.Collection) extends the "Iterable" interface. Hence, all collections in Java are candidate for "FOR EACH LOOP".

//Code

//Define a Collection

Collection<String> collection = new ArrayList<String>();

//Add elements in collection

collection.add("FIRST");

collection.add("SECOND");

collection.add("THIRD"); 
//Traverse using For each loop 
for(String s : collection) 
{ 
//Print the element 
System.out.println(s); 
} 

//Code End.

Well, Java specification states that any class that implements Iterable interface, is a candidate of "For Each" loop. It means that we can also take advantage of this feature in user defined data structures as well. I googled, but did not find any example for this implementation. So, I am posting an implementation of user defined class that take advantage of this feature.

I have created a class for Linear Link list.
//Code Start
import java.util.Iterator;
/**
 * This class is Java implementation of LinearLinkList. 
 * This class demonstrates the implementation of 
 * for each loop. A data structure must
 * implement Iterable interface in order
 *  to use the for each loop
 * feature of Java 1.5
 *  
 * @author Vineet 
 * @param < T >
 */
public class LinearLinkList< T > implements Iterable< T > {
 /**
  * It represents the header of LinkList. 
  * It is the first node of LinkList.
  */
 private Node< T > head = new Node< T >();
 /**
  * Size of LinkList.
  */
 private int size = 0;


 /**
  * Constructs empty link list.
  */
 public LinearLinkList() {
 }


 /**
  * Evaluates the size of link list.
  * 
  * @return size of link list.
  */
 public int size() {
  return size;
 }


 /**
  * Adds an element at the end of list. 
  * If it is empty list, then element is
  * set in head node.
  * 
  * @param element
  */
 public void add(T element) {
  // If it is empty list, set element in header node.
  if (size() == 0) {
   head.element = element;
  }
  // Else, create a node with this element 
  //and add at the end of list.
  else {
   Node< T > node = new Node< T >();
   node.element = element;
   Node< T > temp = head;
   while (temp.nextNode != null) {
    temp = temp.nextNode;
   }
   temp.nextNode = node;
   temp = null;
  }
  size++;
 }


 /**
  * String representation of Link List.
  */
 @Override
 public String toString() {
  StringBuilder str = new StringBuilder();
  Iterator< T > itr = this.iterator();
  while (itr.hasNext()) {
   str.append(itr.next().toString() + ",");
  }
  str.deleteCharAt(str.lastIndexOf(","));


  return str.toString();
 }


 @Override
 public int hashCode() {
  int hash = (int) (31 * Math.random() + 61 * Math.random());
  return hash;
 }


 /**
  * Returns iterator for this list. It enables it to 
  * be candidate of for each loop.
  */
 @Override
 public Iterator< T > iterator() {
  // TODO Auto-generated method stub
  return new Itr();
 }


 /**
  * Finds the element at index position in list.
  * 
  * @param index
  *            position of element to be sought.
  * @return Element at position index
  */
 public T get(int index) {
  Node< T > temp = head;
  while (index > 1) {
   temp = temp.nextNode;
   index--;
  }
  return temp.element;
 }


 /**
  * This class is iterator for this Link List.
  * It enables the navigation of link list.
  * 
  * @author Vineet
  * 
  */
 private class Itr implements Iterator< T > {
  private int cursor = 0;
  private Node< T > temp = head;


  @Override
  public boolean hasNext() {
   return cursor++ < size();
  }


  @Override
  public T next() {
   T element = temp.element;
   temp = temp.nextNode;
   return element;
  }


  @Override
  public void remove() {
  }


 }


 private static class Node< T > {


  T element;
  Node< T > nextNode;


 }


 public static void main(String[] args) {


  LinearLinkList< String > test = new LinearLinkList< String >();
  test.add("First");
  test.add("Second");
  test.add("Third");
  test.add("Fourth");
  test.add("Fifth");


  // Now it will work with For Each loop
  for (String s : test) {
   System.out.println(s);
  }
  System.out.println(test);
 }


}



//Code Ends