ArrayList
Add element to specified index of ArrayList example
In this example we shall show you how to add an element to a specified index of an ArrayList. To add an element to a specified index of an ArrayList one should perform the following steps:
- Create a new ArrayList.
- Populate the arrayList with elements, using
add(E e)
API method of ArrayList. - Invoke
add(int index, E element)
API method of ArrayList. The method inserts the specified element at the specified position in this list, without overwriting the element previously at the specified index, but by shifting the existing elements to right side and increasing the list size by 1,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.ArrayList; public class AddElementToSpecifiedIndexOfArrayList { public static void main(String[] args) { // Create an ArrayList and populate it with elements ArrayList arrayList = new ArrayList(); arrayList.add("element_1"); arrayList.add("element_2"); arrayList.add("element_3"); /* To add an element at the specified index of ArrayList use void add(int index, Object obj) method. This method does NOT overwrite the element previously at the specified index in the list rather it shifts the existing elements to right side increasing the list size by 1. */ arrayList.add(1,"new_element"); System.out.println("Elements in ArrayList :"); for(int i=0; i < arrayList.size(); i++) System.out.println(arrayList.get(i)); } }
Output:
Elements in ArrayList :
element_1
new_element
element_2
element_3
This was an example of how to add an element to a specified index of an ArrayList in Java.