How to Insert Element at Specific Position in Array in Java

How to Insert an element at a specific position in an Array in Java? Here we will see examples to insert an element to the array at index. To insert an element at the end see:- Add element in array Java.

We can insert an element at a specific position in two different ways,
a) Using a new array
b) With the help of ArrayList.

Example:-
Array = {10, 20, 30, 40, 50};
Element to be inserted = 99;
Position = 3;
Final result = {10, 20, 30, 99, 40, 50};

Insert element in Array using new Array in Java

In this approach,
a) Take a position and new array element.
b) Create a new array with the size of n+1, where n is the size of the original array.
c) Copy the element of the original array to the new array until position-1 index.
d) Insert an element at position index
e) Copy remaining elements of original array to new array
f) Return the new array

import java.util.Arrays;
public class ArrayTest {

   // method to add element to array and return new array
   public static int[] addElement(int[] arr,
                          int element, int position) {
      
      // create new array
      int temp[] = new int[arr.length+1];
      
      // add elements to new array
      for (int i=0, j=0; i < temp.length; i++) {
         if(i == position) {
            temp[i] = element;
         } else {
            temp[i] = arr[j++];
         }
      }
            
      // return array
      return temp;
   }

   public static void main(String[] args) {
      // original array
      int arr[] = {10, 20, 30, 40, 50};
      
      // new element to be added
      int element = 99;
      
      // position to be inserted
      // Array index start from 0, not 1
      int position = 3;
      
      // display old array
      System.out.println("Original array: " + Arrays.toString(arr));
      
      // add element 
      arr = addElement(arr, element, position);
      
      // display new array
      System.out.println("New array: " + Arrays.toString(arr));
   }
}

Output:-

Original array: [10, 20, 30, 40, 50]
New array: [10, 20, 30, 99, 40, 50]

The logic to add all elements of the original array and new element at a specific position also can be written as,

// method to add element to array and return new array
public static int[] addElement(int[] arr, int element, int position) {

   // create new array
   int temp[] = new int[arr.length+1];

   // add elements to new array
   for (int i = 0; i < temp.length; i++) {
      if (i < position) 
         temp[i] = arr[i]; 
      else if (i == position) 
         temp[i] = element; 
      else
         temp[i] = arr[i - 1];
   }

   // return array
   return temp;
}

With Help of ArrayList

We can also do the same using ArrayList. The ArrayList class contains an in-built method add(position, element) which can be used to insert an element at the specified position. But for this, we have to perform the required conversions.

In this approach, the array should be of wrapper type (Integer, Double, Float, and e.t.c.), not of primitive types. Because collections classes don’t work directly with primitive types.

In this approach the operations can be performed as,
a) Take the array, position, and element which should be inserted.
b) Create an ArrayList by using the original array.
c) Use add(position, element) method to insert an element at the specified position.
d) Convert the list to the array and return it.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayTest {

   // method to add element to array and return new array
   public static Integer[] addElement(Integer[] arr,
                     int element, int position) {
      
      // create ArrayList
      List<Integer> list = 
            new ArrayList<Integer>(Arrays.asList(arr));
      
      // add element at specificed position
      list.add(position, element);

      // return array
      return list.toArray(arr);
   }

   public static void main(String[] args) {
      // original array
      Integer arr[] = {10, 20, 30, 40, 50};
      
      // new element to be added
      int element = 99;
      
      // position to be inserted
      // Assuming array start from 1, not 0
      int position = 3;
      
      // display old array
      System.out.println("Original array: " + Arrays.toString(arr));
      
      // add element 
      arr = addElement(arr, element, position);
      
      // display new array
      System.out.println("New array: " + Arrays.toString(arr));
   }
}

Output:-

Original array: [10, 20, 30, 40, 50]
New array: [10, 20, 30, 99, 40, 50]

In these examples, to display the array we have used the Arrays.toString() method. The Arrays.toString() method returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets “[]” and the adjacent elements are separated by the characters “, ” (a comma followed by a space). It Returns “null” if the passed array is null. Learn more:- Arrays.toString() method in Java

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply