How to insert an object in an ArrayList at a specific position

JavaArraylist

Java Problem Overview


Suppose I have an ArrayList of objects of size n. Now I want to insert an another object at specific position, let's say at index position k (is greater than 0 and less than n) and I want other objects at and after index position k to shift one index position ahead. So is there any way to do this directly in Java. Actually i want to keep the list sorted while adding new object.

Java Solutions


Solution 1 - Java

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)
   

This method replaces the element at the specified position in the list with the specified element, and returns the element previously at the specified position.

Solution 2 - Java

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

Solution 3 - Java

Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:

http://tpcg.io/0KmArS

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list
      arrlist.add(15, 15);
      arrlist.add(22, 22);
      arrlist.add(30, 30);
      arrlist.add(40, 40);

      // adding element 25 at third position
      arrlist.add(2, 25);
        
      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
   }
}

> $javac com/tutorialspoint/ArrayListDemo.java > > $java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo > > Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0 > at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) > at java.util.ArrayList.add(ArrayList.java:473) > at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

Solution 4 - Java

From Oracle Official Documentation

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

Solution 5 - Java

Actually the way to do it on your specific question is arrayList.add(1,"INSERTED ELEMENT"); where 1 is the position

Solution 6 - Java

You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.

For convenience, you may use this extension function in Kotlin

/**
 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
 */
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {
        add(element)
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarshveer SinghView Question on Stackoverflow
Solution 1 - JavaCloudyMarbleView Answer on Stackoverflow
Solution 2 - JavaJaldip KatreView Answer on Stackoverflow
Solution 3 - JavaAndrewView Answer on Stackoverflow
Solution 4 - JavaAbdul Basit RishiView Answer on Stackoverflow
Solution 5 - JavaSergio LópezView Answer on Stackoverflow
Solution 6 - JavaLeonid UstenkoView Answer on Stackoverflow