.add()
Published Jun 30, 2022
Contribute to Docs
The .add()
method adds an item to the underlying collection of a ListIterator
object. This method adds the item before the next element that would be returned by the .next()
method.
Syntax
myListIterator.add(value);
Where myListIterator
is a ListIterator
object, and value
is the object to add to the underlying collection.
Example
This example populates an ArrayList
, then inserts values between the existing values in the collection:
import java.util.*;public class Example {public static void main(String args[]) {// Create a new ArrayListArrayList l = new ArrayList();// Add some items to the ArrayListl.add(1);l.add(2);l.add(3);l.add(4);l.add(5);ListIterator i = l.listIterator();// Loop through ArrayList contentswhile(i.hasNext()) {int item = (Integer) i.next();i.add(item * 2);}System.out.println(l);}}
This results in the following output:
[1, 2, 2, 4, 3, 6, 4, 8, 5, 10]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.