How can I insert an element in array at a given position?

As we know an array in Java is a fixed-size object, once it created its size cannot be changed. So if you want to have a resizable array-like object where you can insert an element at a given position you can use a java.util.List object type instead.

This example will show you how you can achieve array insert using the java.util.List and java.util.ArrayList object. Let see the code snippet below.

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayInsert {
    public static void main(String[] args) {
        // Creates an array of integer value and prints the 
        // original values.
        Integer[] numbers = new Integer[]{1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " + 

        // Creates an ArrayList object and add the entire content
        // of numbers array into the list. We use the 
        // add(index, element) method to add element=5 at index=3.
        List<Integer> list = new ArrayList<>();
        list.add(3, 5);

        // Converts back the list into array object and prints 
        // the new values.
        numbers = list.toArray(new Integer[list.size()]);
        System.out.println("After insert    : " + Arrays.toString(numbers));

In the code snippet above the original array of Integer numbers will be converted into a List, in this case we use an ArrayList, by adding all elements of the array into the list using the List.addAll() method. The Arrays.asList() can be use to convert an array into a collection type object.

Next we insert a new element into the List using the add(int index, E element) method. Where index is the insert / add position and element is the element to be inserted. After the new element inserted we convert the List back to the original array.

Below is the result of the code snippet above:

Original numbers: [1, 2, 3, 8, 13, 21]
After insert    : [1, 2, 3, 5, 8, 13, 21]

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

Leave a Reply