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.
		 */
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);

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

		/*
		 * 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)
			System.out.println(i);

	}
}

 

By | 2012-09-18T13:34:30+00:00 September 18th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment