articles

Home / DeveloperSection / Articles / Iterator in Java

Iterator in Java

Manoj Pandey1861 14-Apr-2015

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:

·  Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

·  Method names have been improved.

In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. We can say that it contain instance of collections may be arrayList, List etc.

 For example
  List myList=new ArrayList ( );
  mylist.add("Data1");
  mylist.add("Data2");
  mylist.add("Data3");
  mylist.add(1
  mylist.add(2);
  Iterator iter = mylist.iterator();

 In Iterator have multiple useful methods which help us to getting item from list

·   iter.hasNext()-: Returns true if the iteration has more elements.

·    iter.next() -: Returns the next element in the iteration

 Here I am creating a sample of iterator in java. 

import java.util.ArrayList;

import java.util.Iterator;

 

public class Sample {

     static ArrayList mylist;

 

     public static void main(String args[]) {

           mylist = new ArrayList();

           mylist.add("Data1");

           mylist.add("Data2");

           mylist.add("Data3");

           mylist.add(1);

           mylist.add(2);

           Iterator iter = mylist.iterator();

 

           while (iter.hasNext()) {

                Object item = iter.next();

                System.out.println(item);

           }

          

 

     }

 

}

 

An iterator is an abstraction over how a collection is implemented. It lets you go over the whole collection one item at a time, optionally removing items.

The disadvantage of an Iterator is that it can be a lot slow if you DO know the underlying implementation. For example using an Iterator for an ArrayList is considerable slower than just calling ArrayList.get(i) for each element. Whether this matters much depends on what the code is doing.


Updated 05-Dec-2017

Leave Comment

Comments

Liked By