Java Iterator

Last modified on October 11th, 2014 by Joe.

To generate successive elements from a series, we can use java iterator. It is an improvement over Enumeration interface. Iterator takes the place of Enumeration since jdk 1.2

It is a nice utility for collections. Every collection is unique on its own and imagine if we have have to write logic on our own for every collection when there is a need to iterate it. Instead, java forces a collection to deliver an iterator.

These nice utilities makes java lovable, isn’t it?

Important points to note:

We can iterate only in one direction

Iteration can be done only once. If you reach the end of series its done. If we need to iterate again we should get a new Iterator.

Iterator Example without Generics

package com.javapapers; import java.util.ArrayList; import java.util.Iterator; public class ExampleIterator { public static void main(String args[]){ ArrayList animal = new ArrayList(); animal.add("Horse"); animal.add("Lion"); animal.add("Tiger"); Iterator animalItr = animal.iterator(); while(animalItr.hasNext()) { String animalObj = (String)animalItr.next(); System.out.println(animalObj); } } }

Without generics, Iterator returns the Object and we need to typecast it.



Iterator Example using Generics

package com.javapapers; import java.util.ArrayList; public class ExampleIterator { public static void main(String args[]){ ArrayList animal = new ArrayList (); animal.add("Horse"); animal.add("Lion"); animal.add("Tiger"); for(String animalObj : animal) { System.out.println(animalObj); } } }

Output:

Horse

Lion

Tiger

Look how simple it is. There is no reference to the Iterator explicitly since we are using for-each of generics.

Iterable and Iterator

To make an object iterable it needs to emit an Iterator object. To enforce this contract, Iterator interface is to be used. It contains a method named iterator() and it returns Iterator. Hence, any class that implements Iterable will return an Iterator.

public interface Collection<E> extends Iterable<E> {

For example take any Collection. A Collection is an interface that represents container for series of elements. Every collections like ArrayList, Vector implements Collection and so Iterator.

One advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax.

Removing elements using Iterator

Iterator has a remove method using which we can delete elements from the underlying object.

It removes the last element returned by the iterator.

Difference between Iterator and Enumeration interfaces

remove() method is introduced in iterator. Using this method we can remove element from the underlying collection which we are iterating. Enumeration has two methods and both are available in iterator. Method names for both of them are shortened.

ListIterator an even better Iterator for a List containing more utility methods like getting index of elements and adding elements to the base object. Using ListIterator we can iterate in both the directions.

ConcurrentModificationException

Look at the following code, it throws ConcurrentModificationException. We cannot add or remove elements to the underlying collection when we are using an iterator.

package com.javapapers; import java.util.ArrayList; public class ExampleIterator { public static void main(String args[]){ ArrayList animal = new ArrayList (); animal.add("Horse"); animal.add("Lion"); animal.add("Tiger"); for(String animalObj : animal) { System.out.println(animalObj); animal.add("Hyena"); } } } Output: Horse Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) at com.javapapers.ExampleIterator.main(ExampleIterator.java:13)

Implementing our own Custom Iterator

We will create our own custom class and make it implement Iterable, so that it returns an Iterator using which we can iterate the elements.

package com.javapapers; import java.util.ArrayList; import java.util.Iterator; public class AnimalIterator<String> implements Iterator<Object> { private ArrayList<?> animal; private int position; public AnimalIterator(Animal animalBase) { this.animal = animalBase.getAnimal(); } @Override public boolean hasNext() { if (position < animal.size()) return true; else return false; } @Override public Object next() { Object aniObj = animal.get(position); position++; return aniObj; } @Override public void remove() { animal.remove(position); } }

package com.javapapers; import java.util.ArrayList; import java.util.Iterator; public class Animal implements Iterable<String> { private ArrayList<String> animal = new ArrayList<String>(); public Animal(ArrayList animal){ this.animal = animal; } public ArrayList getAnimal() { return animal; } @Override public Iterator<String> iterator() { return new AnimalIterator(this); } }

package com.javapapers; import java.util.ArrayList; public class TestIterator { public static void main(String args[]) { ArrayList<String> animalList = new ArrayList(); animalList.add("Horse"); animalList.add("Lion"); animalList.add("Tiger"); Animal animal = new Animal(animalList); for (String animalObj : animal) { System.out.println(animalObj); } } }

Output:

Horse

Lion

Tiger