Thursday, October 24, 2013

Java: Iterator

The Iterator interface is a member of the  Java Collections Framework.

Important notes about Iterator:

  • We can iterate in only one direction.
  • Iteration can be done only once. If you reach the end of the collection its done. If we need to iterate again we should get a new Iterator.
  • We cannot add or remove elements to the underlying collection when we are using an iterator except by calling the Iterator's remove() method.


Here is the Iterator interface documentation.

ITERATOR WITHOUT GENERICS USING FOR-LOOP

import java.util.ArrayList;
import java.util.Iterator;

public class ExampleIterator {

  public static void main(String args[]){
    List brands = new ArrayList();
    brands.add("Honda");
    brands.add("Nissan");
    brands.add("Toyota");

    for (Iterator iter = brands.iterator(); iter.hasNext();) {
    String brand = (String)iter.next();
      System.out.println(brand);
    } 
  }

}

Note: Without generics, Iterator returns an Object so you need to typecast it.


ITERATOR WITH GENERICS USING FOR-LOOP

public class ExampleIterator {

  public static void main(String args[]){
    List<String> brands = new ArrayList<String>();
    brands.add("Honda");
    brands.add("Nissan");
    brands.add("Toyota");

    for (Iterator<String> iter = brands.iterator(); iter.hasNext();){
    String brand = iter.next();      
      System.out.println(brand);
    }
  }

}


ITERATOR WITHOUT GENERICS USING WHILE-LOOP

import java.util.ArrayList;
import java.util.Iterator;

public class ExampleIterator {

  public static void main(String args[]){
    List brands = new ArrayList();
    brands.add("Honda");
    brands.add("Nissan");
    brands.add("Toyota");

    Iterator iter = brands.iterator();

    while(iter.hasNext()) {
      String brand = (String)iter.next();
      System.out.println(brand);
    }
  }

}


ITERATOR WITH GENERICS USING WHILE-LOOP

import java.util.ArrayList;

public class ExampleIterator {

  public static void main(String args[]){
    List<String> brands = new ArrayList<String>();
    brands.add("Honda");
    brands.add("Nissan");
    brands.add("Toyota");

    Iterator<String> iter = brands.iterator();

    while (iter.hasNext()){
      String brand = iter.next();
      System.out.println(brand);
    }
  }

}


ITERATE USING FOR-EACH OF GENERICS
(No explicit reference to the Iterator object)

import java.util.ArrayList;

public class ExampleIterator {

  public static void main(String args[]){
    List<String> brands = new ArrayList<String>();
    brands.add("Honda");
    brands.add("Nissan");
    brands.add("Toyota");

    for(String brand : brands) {
      System.out.println(brand);
    }
  }

}



No comments:

Post a Comment