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:

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.

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

Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

Leave a Reply

Your email address will not be published. Required fields are marked *