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.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, 1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " +
                Arrays.toString(numbers));

        // Creates an ArrayList object and initialize its values with the entire
        // content of numbers array. We use the add(index, element) method to add
        // element = 5 at index = 4.
        List<Integer> list = new ArrayList<>(Arrays.asList(numbers));
        list.add(4, 5);

        // Converts back the list into array object and prints the new values.
        numbers = list.toArray(new Integer[0]);
        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, we initialized the ArrayList by passing all elements of the array into the list constructor. The Arrays.asList() can be used 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, 1, 2, 3, 8, 13, 21]
After insert    : [1, 1, 2, 3, 5, 8, 13, 21]
Wayan

Leave a Reply

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