Java ArrayList.listIterator() – Examples

In this tutorial, we will learn about the Java ArrayList.listIterator() method, and learn how to use this method to get the ListIterator for the elements in this ArrayList, with the help of examples.

listIterator()

ArrayList.listIterator() returns a list iterator over the elements in this ArrayList (in proper sequence).

Syntax

The syntax of listIterator() method is

ArrayList.listIterator()

Returns

The method returns ListIterator<E> object.

Example 1 – listIterator()

In this example, we will define an ArrayList of Strings and initialize it with some elements in it. We will use ArrayList.listIterator() method to get the ListIterator for the elements in this ArrayList.

Java Program

import java.util.ArrayList;
import java.util.ListIterator;

public class Example {
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>();  
		arrayList.add("a");  
		arrayList.add("b");  
		arrayList.add("c"); 
		arrayList.add("d");    

		ListIterator<String> listIterator = arrayList.listIterator(); 
		while (listIterator.hasNext()) { 
			System.out.println(listIterator.next()); 
		} 
	}
}

Output

a
b
c
d

listIterator(int index)

ArrayList.listIterator() returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

Syntax

The syntax of listIterator() method with the index argument is

ArrayList.listIterator(int index)

where

ParameterDescription
indexThe index of the first element to be returned from the list iterator.

Returns

The method returns ListIterator<E> object.

Example 2 – listIterator(int index)

In this example, we will define an ArrayList of Strings and initialize it with some elements in it. We will use ArrayList.listIterator(index) method to get the ListIterator for the elements from index=2 in this ArrayList.

Java Program

import java.util.ArrayList;
import java.util.ListIterator;

public class Example {
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>();  
		arrayList.add("a");  
		arrayList.add("b");  
		arrayList.add("c"); 
		arrayList.add("d");    

		int index = 2;
		ListIterator<String> listIterator = arrayList.listIterator(index); 
		while (listIterator.hasNext()) { 
			System.out.println(listIterator.next()); 
		} 
	}
}

Output

c
d

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList.listIterator() method, and also learnt how to use this method with the help of Java example programs.