You can use this arraylist class method to insert an item at a specific location in an arraylist.

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]

You can use thisArrayListclass method to insert an item at a specific location in anArrayListWhat does this code do?int[] x = {0, 1, 2, 3, 4, 5};What does a search algorithm do?Ifnumbersis a two-dimensional array, which of the following would give the number of columns in rowrThink numbers[?].lengthGiven the following two-dimensional array declaration, What occurs?int[][] numbers = new int[6][9];What will be the result of the following code?final int ARRAY_SIZE = 5;float[] x = float[ARRAY_SIZE];for(int i = 1; i <= ARRAY_SIZE; i++){x[i] = 10.0;}For the following code, what would be the value ofstr[2]String[] str = {"abc", "def", "ghi", "jkl"};What will be the result of the following code?int[] numbers = {40, 3, 5, 7, 8, 12, 10};int value = numbers[0];for (int i = 1; i < numbers.length; i++){if (numbers[i] < value)value = numbers[i];}What is a ragged array?What will be the result of the following code?int[] numbers = {50, 10, 15, 20, 25, 100, 30};int value = 0;for (int i = 0; i < numbers.length; i++)value += numbers[i];What is the value ofscores[2][3]in the following array?.??


The java.util.ArrayList.add(int index, E elemen) method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).

Declaration

Following is the declaration for java.util.ArrayList.add() method

public void add(int index, E element)

Parameters

  • index − The index at which the specified element is to be inserted.

  • element − The element to be inserted.

Return Value

This method does not return any value.

Exception

IndexOutOfBoundsException − if the index is out of range.

Example

The following example shows the usage of java.util.ArrayList.add(index,E) method.

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); arrlist.add(22); arrlist.add(30); arrlist.add(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); } } }

Let us compile and run the above program, this will produce the following result −

Number = 15 Number = 22 Number = 25 Number = 30 Number = 40

java_util_arraylist.htm