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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button