Java Utility Library

Java ArrayList - iterator() Method



The java.util.ArrayList.iterator() method returns an iterator over the elements in the list in proper sequence.

Syntax

public Iterator<E> iterator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns an iterator over the elements in this list in proper sequence.

Exception

NA.

Example:

In the example below, the java.util.ArrayList.iterator() method returns an iterator over the elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating the ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);

    //print the content of the ArrayList
    System.out.println("MyList contains: " + MyList);

    //creating an iterator
    Iterator<Integer> itr = MyList.iterator();

    //print the content of the iterator
    System.out.println("The iterator values are: ");
    while(itr.hasNext())
      System.out.println(itr.next()); 
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40]
The iterator values are: 
10
20
30
40

❮ Java.util - ArrayList