ArrayList listIterator() method in java

Let’s learn ArrayList listIterator() method in java.

ArrayList listIterator() method in java

listIterator() method of ArrayList class 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)

Parameters:

index index of the first element to be returned from the list iterator (by a call to next).

Throws:

IndexOutOfBoundsException – if the index is out of range(index < 0 || index > size()).

Also read – ArrayList in java

Now let’s see example on ArrayList listIterator() method.

import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListListIteratorMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("plum");
      al.add("apple");
      al.add("orange");
      al.add("mango");
      al.add("pineapple");
      System.out.println(al);
      ListIterator<String> iterate = al.listIterator(1);
      while(iterate.hasNext())
      {
         String str = iterate.next();
         System.out.println(str);
      }
   }
}


Output:

[plum, apple, orange, mango, pineapple]
apple
orange
mango
pineapple


Let’s see example on listIterator() method IndexOutOfBoundsException.

import java.util.ArrayList;
import java.util.ListIterator;
public class ArrayListListIteratorMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("plum");
      al.add("apple");
      al.add("orange");
      al.add("mango");
      al.add("pineapple");
      System.out.println(al);
      ListIterator<String> iterate = al.listIterator(5);
      System.out.println(iterate.hasNext());
      iterate = al.listIterator(6);
   }
}


Output:

[plum, apple, orange, mango, pineapple]
false
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 6, Size: 5