![]() |
VOOZH | about |
The listIterator() method of ArrayList class in Java is used to return a ListIterator for traversing the elements of the list in proper sequence. The iterator allows both forward and backward traversal of the list.
Example 1: Here, we use the listIterator() method to obtain a ListIterator over all elements in an ArrayList.
Iterating through the list: A B C D
Explanation: In the above example, we use a ListIterator to iterate over an ArrayList of Strings i.e. "A", "B", "C", and "D". It prints each element of the list sequentially using the hasNext() and next() methods of the ListIterator.
// Obtain a ListIterator over all elements
public ListIterator<E> listIterator()// Obtain a ListIterator starting at a specified index
public ListIterator<E> listIterator(int index)
There are two versions of listIterator() method i.e. one to obtain a ListIterator over all elements and one to obtain a ListIterator starting at a specified index.
Example 2: Here, we use the listIterator() method to obtain a ListIterator starting at a specified index.
Iterating from index 2: C D
Example 3: Here, we will see how the below code handles an invalid index with listIterator() method.
ArrayList: [A, B, C, D] Size of ArrayList: 4 Trying to getListIterator from index 7 Exception thrown: java.lang.IndexOutOfBoundsException: Index: 7, Size: 4