Iterator in Java

In the previous post, we have learnt about TreeMap in java. In this post, we will learn about the Iterator in java.

Iterator is used for iterating(looping) over collections classes in java like HashMap, TreeMap, LinkedList, ArrayList etc. We will learn about iterator in details like what is iterator , how to use it and how it is different from Enumeration which was used to iterate over the legacy classes.

Let’s understand Iterator with examples for generic and non-generic datatypes.

Problem when we iterate with Non-generic list:

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

public class IteratorEx {

	public static void main(String[] args) {

		ArrayList list = new ArrayList();

		list.add("Name");
		list.add("City");
		list.add("Country");
		
		
		list.add(new Integer(2));
		
		Iterator iter = list.iterator();
		while(iter.hasNext()){
			String element = (String) iter.next();
			System.out.println(element);
		}
	}
}

Output:

Exception in thread “main” Name City
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String Country at com.testingpool.demo2.IteratorEx.main(IteratorEx.java:21)

Iterate over a generic list:

Since java 1.5 , Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.

Now if, you add integer element it will give compile time error.

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

public class IteratorEx {

	public static void main(String[] args) {

		ArrayList<String> list = new ArrayList<String>();

		list.add("Name");
		list.add("City");
		list.add("Country");

		
		Iterator iter = list.iterator();
		while(iter.hasNext()){
			String element = (String) iter.next();
			System.out.println(element);
		}
	}
}

Output:

Name
City
Country


Difference between Iterator and Enumeration:

Iterator differs from Enumeration in following ways.

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved. hashNext() method of iterator replaced hasMoreElements() method of enumeration, similarly next() replaced with nextElement().

 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".