What is the ListIterator.add method in Java?
The
ListIteratoris 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 thecurrentElementlikeIterator.
The add method inserts the passed element into the list.
The element is inserted:
- Before the element which will be returned on calling the
next()method on the list iterator. (In other words, the new element will be inserted on the index that is returned by calling thenextIndexmethod). - After the element which will be returned on calling the
previous()method on the list iterator. (In other words, the new element will be inserted after theindexthat is returned by calling thepreviousIndexmethod 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.
Syntax
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.
Code
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);}}
Explanation
-
In lines 1 and 2: Import the
ListIteratorandArrayListclass. -
From lines 7 to 11: Create a new
ArrayListobject with namelistand add three elements10,20,30to it using theaddmethods. -
In line 14: Use the
listIteratormethod of theArrayListobject to get theListIteratorfor the ArrayList. -
In line 15: Use the
nextIndexmethod of thelistIteratorobject to get the next element index which will be returned on calling thenextmethod. We will get0as result. -
In line 16: Use the
previousIndexmethod of thelistIteratorobject to get the previous element index which will be returned on calling thepreviousmethod. We will get-1because there is no element present before the cursor of thelistIterator. -
In line 18: Use the
addmethod with11as an argument. This method will add11in the index of thenextIndex. In our case,nextIndexis0so the element will be inserted in index0. Now the cursor will be pointing to index0. If we callnextIndexagain we will get1and if we callpreviousIndexwe will get0.