Collections

Java ArrayList ListIterator example

Java ArrayList ListIterator example shows how to iterate ArrayList using ListIterator. 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 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 backward direction.

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

Java ArrayList ListIterator Example

Output

In above example, we first iterated the ArrayList in forward direction which put the cursor at the end of the list. We immediately iterated the ArrayList in 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 current cursor position.

Output

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

Join 1000+ fellow learners! Enter your email address below: