The
ListIterator
is an iterator which we can traverse the list in both directions (forward and backward), modify the list, and get the index of the iterator’s current position. Also, it doesn’t have thecurrentElement
likeIterator
.
The add
method inserts the passed element into the list.
The element is inserted:
next()
method on the list iterator. (In other words, the new element will be inserted on the index that is returned by calling the nextIndex
method).previous()
method on the list iterator. (In other words, the new element will be inserted after the index
that is returned by calling the previousIndex
method if it is not -1
).The new element is inserted before the implicit cursor. So the call to the next()
method is unaffected. Also, the newly inserted element is returned if we call the previous()
method.
void add(E e)
This method takes the element to be inserted into the list as an argument.
This method does not return any value.
The code below demonstrates how to use the add
method:
import java.util.ListIterator;import java.util.ArrayList;class Add {public static void main(String[] args) {// Initialize arrayArrayList<Integer> list = new ArrayList<>();list.add(10);list.add(20);list.add(30);System.out.println("The array list is " + list);// ListIteratorListIterator<Integer> it = list.listIterator();System.out.println("Calling it.nextIndex() " + it.nextIndex());System.out.println("Calling it.previousIndex() " + it.previousIndex());// Add 11 using ListIteratorit.add(11);System.out.println("\nAdding using it.add(11)");System.out.println("\nCalling it.nextIndex() " + it.nextIndex());System.out.println("Calling it.previousIndex() " + it.previousIndex());System.out.println("The array list is " + list);}}
In lines 1 and 2: Import the ListIterator
and ArrayList
class.
From lines 7 to 11: Create a new ArrayList
object with name list
and add three elements 10,20,30
to it using the add
methods.
In line 14: Use the listIterator
method of the ArrayList
object to get the ListIterator
for the ArrayList.
In line 15: Use the nextIndex
method of the listIterator
object to get the next element index which will be returned on calling the next
method. We will get 0
as result.
In line 16: Use the previousIndex
method of the listIterator
object to get the previous element index which will be returned on calling the previous
method. We will get -1
because there is no element present before the cursor of the listIterator
.
In line 18: Use the add
method with 11
as an argument. This method will add 11
in the index of the nextIndex
. In our case, nextIndex
is 0
so the element will be inserted in index 0
. Now the cursor will be pointing to index 0
. If we call nextIndex
again we will get 1
and if we call previousIndex
we will get 0
.