How to Add Elements to ArrayList at Specified Index Location in Java


Here we may learn about how to add an element at specified index of ArrayList object with add method in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;

public class AddElementSpecifiedIndex {

	public static void main(String[] args) {

		ArrayList alist = new ArrayList();

		// Add Elements
		alist.add("A");
		alist.add("B");
		alist.add("C");

		// Iterate over the elements of the collection
		for (int i = 0; i < alist.size(); i++) {
			
			String element = (String) alist.get(i);
			System.out.print(element + "t");
		}

		// Add an element "D" at index 1
		alist.add(1, "D");

		System.out.println("n-------------------------");
		
		for (int i = 0; i < alist.size(); i++) {
			
			String element = (String) alist.get(i);
			System.out.print(element + "t");
		}

	}

}

Output:

A	B	C	
-------------------------
A	D	B	C	

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments