Skip to content

Java ArrayList ListIterator example

Java ArrayList ListIterator example shows how to iterate ArrayList using ListIterator. The example also shows how to iterate ArrayList in backward direction using ListIterator.

How to iterate ArrayList using ListIterator?

ArrayList class provides listIterator method which returns a list iterator over its elements.

Once we get the list iterator, we can iterate the ArrayList using hasNext, next, hasPrevious and previous methods.

This method returns true if there are more elements to iterate when iterating the ArrayList in the forward direction.

This method returns the next element in the ArrayList and increments the cursor.

This method returns true if there more elements to iterate when iterating the ArrayList in a backward direction.

This method returns the previous element in the ArrayList and decrements the cursor.

Java ArrayList ListIterator Example

Output

In the above example, we first iterated the ArrayList in the forward direction which put the cursor at the end of the list. We immediately iterated the ArrayList in the backward direction so it started from the end of the ArrayList.

If you want to iterate the list from backward direction without first iterating it in the forward direction then use overloaded listIterator method which accepts the starting position.

This method returns a list iterator over elements of an ArrayList starting at the specified position.

Example

Output

How to remove elements using list iterator?

If you want to remove elements while iterating the ArrayList, use

This method removes the last element that was returned by next or previous method call from the ArrayList.

Output

How to replace elements using list iterator?

If you want to replace elements while iterating the ArrayList, use

This method replaces the last element that was returned by next or previous method call with the specified element in the ArrayList.

Output

How to insert or add elements using list iterator?

If you want to insert or add elements while iterating the ArrayList using list iterator, use

This method inserts an element to the ArrayList at the current cursor position.

Output

This example is a part of the Java ArrayList tutorial with examples and Java ListIterator tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.