Iterator and ListIterator

Java introduces a very cool interface for us, and that is “Iterator”.

So iterator is basically an interface and we can use it to traverse through collections like List, Set.

Generally iterator provides 3 methods

1. hasNext(): This method returns true if collection still have elements to traverse.

2. next(): It will return the next element in the collection and returns as ‘Object’ so we need to make proper casting.

3. remove(): Removes the element from collection.

( Note: If you are using for loop or any other loop to traverse through collection and in that case if you want to remove some element from collection then you will get “ConcurrentModificationException” because Collection will not allow you to modify it while iterating, but this same thing you can achieve by using iterator. Iterator will not complain or throw any exception when you remove some element from collection.
So when you want to modify collection think for Iterator :) )

Java introduces a very cool interface for us, and that is “Iterator”.

So actually an iterator is an interface and we can use it to traverse through collections like List, Set.

so generally iterator provides 3 methods

1. hasNext(): This method returns true if collection has some elements.

2. next(): It will return the next element in the collection and returns as ‘Object’ so we need to make proper casting.

3. remove(): This is something very cool stuff. suppose you are iterating from collection and you want to remove some element then you can do that using this method.

( Note: If you are using for loop to traverse some collection and if you remove some element from the collection while traversing then you will get ConcurrentModificationException, so to avoid this exception use iterator and call remove on element to remove it from collection and you won’t get any exception )

This is all about Iterator. but wait what if you also need to add some elements into collection while iterating ??
Here comes the ListIterator in the picture which can do adding, removing and traversing in both directions.

So ListIterator is also an interface which provides functionality of adding, removing and traversing the collection in both directions.

Below are some methods provided by ListIterator

1. hasNext(): returns true if there is an element to traverse collection in forward direction.

2. hasPrevious(): returns true if there is an element to traverse collection in backward direction.

3. add(): add an element into collection

4. remove(): remove an element from collection

5. previous(): returns the previous element in collection.

6. next(): returns the next element in collection.

This is all about Iterator and ListIterator.

Thanks