Java ArrayList - listIterator() Method
The java.util.ArrayList.listIterator() method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one.
Syntax
public ListIterator<E> listIterator(int index)
Here, E is the type of element maintained by the container.
Parameters
index |
Specify index of the first element to be returned from the list iterator. |
Return Value
Returns a list iterator over the elements in the list (in proper sequence), starting at the specified position in the list.
Exception
Throws IndexOutOfBoundsException, if the index is out of range (index < 0 || index > size()).
Example:
In the example below, the java.util.ArrayList.listIterator() method returns a list iterator over the elements of the given list, starting at the specified position.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); //populating the ArrayList for(int i = 1; i <= 5; i++) MyList.add(i*10); //print the content of the ArrayList System.out.println("MyList contains: " + MyList); //creating listIterator starting at specified index ListIterator itr1 = MyList.listIterator(3); ListIterator itr2 = MyList.listIterator(4); //Forward Traversal System.out.println("Forward Traversal: "); while(itr1.hasNext()) System.out.println(itr1.next()); //Backward Traversal System.out.println("Backward Traversal: "); while(itr2.hasPrevious()) System.out.println(itr2.previous()); } }
The output of the above code will be:
MyList contains: [10, 20, 30, 40, 50] Forward Traversal: 40 50 Backward Traversal: 40 30 20 10
❮ Java.util - ArrayList