Iterator in Java

Let’s learn about Iterator in Java, The iterator is used to iterating the classes in Collection framework. We use an iterator to iterating the elements of the collection classes.

The iterator is an interface. You need to know some important points about Iterator-

  • You can iterate only in one direction.
  • Iteration can be done only once. If you reach the end of series it’s done. If we need to iterate again we should get a new Iterator.


Methods of Iterator interface –

There are only three methods in the Iterator interface. They are:

  • public boolean hasNext() – It returns true if iterator has more elements.
  • public object next() – It returns the element and moves the cursor pointer to the next element.
  • public void remove() – It removes the last elements returned by the iterator.


Let’s see an easy example of Iterator. In this example, We will traverse an ArrayList using iterator –




Using this way we can iterating over collection classes using Iterator interface.

This is all about Iterator interface. In the above example, We are creating an ArrayList named ‘Car’  then we are using Iterator to iterating over Car ArrayList.  Using carItr.hasNext() we are checking is next element present in the ArrayList it will return the boolean value true/false to while loop. If element present this will return true and while will execute otherwise while will terminate. this will return the element to string variable. Later we are printing this String value.

So using this we can use Iterator to iterating the Collection classes.

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

1 Comment
  1. Tom Hank 10:05 PM / May 29, 2017 - Reply

    Nice explanation…

Leave a Reply