Code Base

Java ArrayList add element at specified index example

import java.util.ArrayList;
import java.util.List;

public class AddElementAtSpecifiedIndex {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();

		 * add() method appends the specified element to the end of given list.

		System.out.println("Elements in Arraylist");
		 * As ArrayList implements Iterable ArrayList can be used in extended
		 * For Loop
		for (int i : list)

		 * ArrayList has an Overloaded method of add(). This overloaded
		 * method(add(index, element)) inserts the specified element at the
		 * specified position in given list. It shifts the element currently at
		 * that position and any subsequent elements to the right (If it exist).
		 * Note*: Index of ArrayList starts with 0.

		list.add(2, 6);// This will add element 6 at index 2 or 3rd position.

		System.out.println("nAfter adding element in ArrayList");
		for (int i : list)




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top Search
Social Share