ArrayList: Iteration using ListIterator
Let's discuss how to iterate an ArrayList using a ListIterator.
We'll cover the following
ListIterator
The Iterator
provides very limited capabilities as we can iterate only in the forward direction and we can’t update or insert an element to the list while iterating. To overcome these problems, we can use ListIterator
. The listIterator()
method returns an object of type ListIterator which can then be used to iterate the ArrayList.
Below are the methods that are available in the ListIterator interface.
-
hasNext()
— This method is used to check if there is a next element in the list when the list is iterated in the forward direction. -
next()
— This method returns the next element in the list and advances the cursor position. -
hasPrevious()
— This method is used to check if there is a next element in the list when the list is iterated in the backward direction. -
previous()
— This method returns the previous element in the list and moves the cursor position backward. -
nextIndex()
— This method returns the index of the element that would be returned by a subsequent call tonext()
. It returns the list size if the list iterator is at the end of the list. -
previousIndex()
— This method returns the index of the element that would be returned by a subsequent call toprevious()
. It returns -1 if the list iterator is at the beginning of the list. -
remove()
— This method removes the last element that was returned bynext()
orprevious()
from the list. This call can only be made once per call tonext()
orprevious()
. It can be made only ifadd()
has not been called after the last call tonext()
orprevious()
. -
set(E e)
— This method replaces the last element returned bynext()
orprevious()
with the specified element. This call can be made only if neitherremove()
noradd()
have been called after the last call tonext()
orprevious()
. -
add(E e)
— This method inserts the specified element into the list. The element is inserted immediately before the element that would be returned bynext()
, if any, and after the element that would be returned byprevious()
, if any.
The below example shows ListIterator
working.
Get hands-on with 1400+ tech skills courses.