How to Add Or Insert an Element to ArrayList in Java


In this example, we will learn how to add or insert an element while traversing through elements of ArrayList using ListIterator in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.ListIterator;

public class AddAnElementUsingListIterator {

	public static void main(String[] args) {
		
		//create ArrayList.
		ArrayList arrayList = new ArrayList();

		arrayList.add("A");
		arrayList.add("B");
		arrayList.add("C");
		arrayList.add("D");
		
		System.out.println("Before inserting element, ArrayList contains");
		for(int intIndex = 0; intIndex < arrayList.size(); intIndex++) 
		{
			System.out.println(arrayList.get(intIndex));
		}
		
		//Get an object of ListIterator using listIterator() method.
		ListIterator listIterator = arrayList.listIterator();
		
		//Add an element.
		listIterator.add("X");
		
		System.out.println("After inserting element, ArrayList contains");
		for(int intIndex = 0; intIndex < arrayList.size(); intIndex++) 
		{
			System.out.println(arrayList.get(intIndex));
		}
	}

}

Output:

Before inserting element, ArrayList contains
A
B
C
D
After inserting element, ArrayList contains
X
A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments