Add an item to ArrayList using ListIterator
This example shows how to add or insert an element into an ArrayList while browsing the list using ListIterator. Use the add(Object o) of the ListIterator class to insert the element just before the element that will be returned by the next call to the next().
The add() can raise the exception UnsupportedOperationException if the operation is not supported by ListIterator.
The add() can raise the exception UnsupportedOperationException if the operation is not supported by ListIterator.
import java.util.ArrayList;Runtime:
import java.util.ListIterator;
public class ArrayListListIterator{
public static void main(String[] args) {
// Create an ArrayList
ArrayListaList = new ArrayList ();
//add strings to ArrayList
aList.add("a");
aList.add("b");
aList.add("c");
aList.add("d");
aList.add("e");
System.out.println("ArrayList before insertion:");
for(String e:aList)
System.out.println(e);
//get a listiterator object by calling the listIterator()
ListIterator listIterator = aList.listIterator();
//the new item will be inserted just after the object "a"
listIterator.next();
//add new element
listIterator.add("New element");
System.out.println("ArrayList after insert:");
for(String e:aList)
System.out.println(e);
}
}
ArrayList before insert:
a
b
c
d
e
ArrayList after insert:
a
New Element
b
c
d
e