Java Program to Add an Element to ArrayList using ListIterator
Last Updated :
15 Dec, 2020
In this article, we will learn how to add an element to ArrayList using ListIterator. The ListIterator is used to return a list iterator over the list elements. The listIterator() returns an iterator over the list from the beginning, but the listIterator(index) returns an iterator over the list from the given index.
Syntax:
// listIterator() method returns an iterator over the list from the beginning
ListIterator<Integer> it = list.listIterator()
// listIterator(index) method returns ans iterator over the list from the given index
ListIterator<Integer> it = list.listIterator(index);
Return Value: This method returns a list iterator over the elements in this list (in proper sequence).
Approach: To add an element to ArrayList using Java ListIterator, the process divided into two parts:
1. Make an iterator.
ListIterator<Integer> it = list.listIterator()
2. Add element using add() method.
it.add(element)
Below is the implementation of the above approach:
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
list.add( 10 );
list.add( 20 );
list.add( 30 );
System.out.println( "Before add 50: " + list);
ListIterator<Integer> it = list.listIterator();
while (it.hasNext()) {
it.add( 50 );
it.next();
}
System.out.println( "After add 50: " + list);
}
}
|
Output
Before add 50: [10, 20, 30]
After add 50: [50, 10, 50, 20, 50, 30]
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
list.add( 10 );
list.add( 20 );
list.add( 30 );
System.out.println( "Before add 50: " + list);
ListIterator<Integer> it = list.listIterator( 1 );
while (it.hasNext()) {
it.add( 50 );
it.next();
}
System.out.println( "After add 50: " + list);
}
}
|
Output
Before add 50: [10, 20, 30]
After add 50: [10, 50, 20, 50, 30]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...