Iterator and List Iterator in Java

Today I am going to explain you the concepts of Iterator and List Iterator in Java, Iterator in Java is an interface belongs to collection framework, It is use to traverse the collection objects. We already know different ways of traversing like for loop, while loop, do while etc. they are index based traversing, as we know java is an object oriented programming language so it provides us a way to traverse the objects, it provides us 3 ways Iterator, List Iterator, Enumeration. We will discuss all three methods one by one.

Iterator:
Iterator in Java is an interface belongs to collection framework it allow us to traverse the collection objects. It has three methods

boolean hasNext(): returns true if  Iterator has more element to iterate.

Object next(): return the next element in the collection.
It is more secure to use hasNext() method before using next() to avoid NoSuchElementException.

remove(): It remove the last element return by the iterator.

Difference between Iterator and List Iterator:
1. Iterator is use to traverse List, Set and Map Objects where as List Iterator is use to traverse list objects.
2. Iterator can iterate elements only in forward direction where as List Iterator can iterate forward as well as in backward direction.
3. Iterator can't replace existing object with new object where as List Iterator can replace existing object with new object.
4. Iterator can't get index of elements where as List Iterator get index of list elements.

We have Enumeration then what is the need of Iterator?
The major difference between Enumeration and Iterator is Iterator has a remove method while Enumeration doesn't. Enumeration acts as Read-only interface because it has the methods only to traverse and fetch the objects where as in iterator we can add and remove objects from collection. 

Example:
Let us assume Employee is a class.

ArrayList list=new ArrayList();
list.add('111','Amit');
list.add('222','Fraz');
list.add('333','Hasan');

Now if we want to iterate the collection object of ArrayList then,

Iterator itr=new Iterator();
while(itr.hasNext()){
Employee emp=(Employee)list.next();
System.out.println("Employee Id:  "+emp.id+"   Employee Name:   "+emp.name);
}

Note: If you have any problem then just drop me a comment.

 

Post a Comment

0 Comments