An iterator is an object that allows the user to hop from the start of a collection to the end, one element at a time, obtaining, modifying or removing each element.
For example, have you ever found yourself with a huge collection of items? Like a stacked bookshelf and you want to go through one book at a time. For each book, you want to see the name of the book before moving onto the next book.
Extending our example to Java, where you might have a collection of objects like an ArrayList
or a hash table
, you can make use of iterators to traverse the collection.
In order to use iterators in Java, one must know the following points:
The first step is to import the java.util.*
library. As the iterator is an interface that is part of the util package, this must be present, as shown on line 1 in the code below.
To declare an iterator, you can make use of the following general statement:
Iterator iterator_name = name_of_collection.iterator()
. This is shown on line 17 in the code snippet belowJava iterators have three methods. They are as follows:
hasNext()
: This returns a boolean value and determines whether the collection has more elements beyond the current position. If it does, then it returns true
next()
: This returns an object which it then equates to the iterator, hence, this method shifts the iterator to the next position
remove()
: This simply deletes the current object in the collection and must be invoked after next()
has been called on the iterator. Otherwise, the iterator itself will point to nothing, resulting in an exception
Now that we know how to use an iterator, the code below shows how to implement the theory:
import java.util.*;class iterators {public static void main( String args[] ) {ArrayList<Integer> arrList = new ArrayList<Integer>();arrList.add(1);arrList.add(2);arrList.add(4);arrList.add(3);System.out.println("arrList contains the following elements:");for(Integer a:arrList){System.out.println(a);}Iterator i = arrList.iterator();//The while loop first checks if a next element is available and then continueswhile(i.hasNext()){//This ensures that the value of the next variable is storedInteger check = (Integer) i.next();if(check==4){//Remove the element if it is equivalent to 4i.remove();System.out.println("4 has been removed from arrList");break;}}System.out.println("Printing elements of arrList again:");for(Integer b:arrList){System.out.println(b);}}}
Free Resources