What is an Iterator in Java? A Java Iterator is an interface that allows you to move through a list of elements within a Java collection. Out sample code below uses an iterator to loop through an ArrayList of String objects. A Java Iterator takes the place of Enumeration in the Java Collections Framework.
You may be wondering what are the advantages of using a Java Iterator over let’s say a Java enhanced for loop. Good question. There are some benefits of the Java Iterator:
- Ability to delete elements from a Collection.
- Ability to move either backward or forward using previous() and next() methods.
- Ability to check for more elements using the hasNext() method.
Java Iterator Source Code
public class JavaArrayListIterator
public static void main(String args)
//Let's create an empty ArrayList
ArrayList<String> jcdArrayList = new ArrayList<String>();
//Now let's add some elements to our ArrayList
//Now define out Iterator
Iterator<String> jcdIterator = jcdArrayList.iterator();
//Loop through or iterate over our collection
String JCD = jcdIterator.next();
Java Iterator Output