Insert an element into an array at the specific index in Java

In this post, we will see how to insert an element into an array at specified index in Java. The insertion should shift the element currently at that index and any subsequent elements to the right by one position.


 

We know that unlike an ArrayList, arrays in Java are fixed-size and non-dynamic. Therefore, insertion of an element at the specified position in an array is not feasible if the array is full. This post provides an overview of some of the available alternatives to accomplish this.

 

1. Naive

We can write our own routine for this simple task. The idea is to declare a new array having one more element and populate it with relevant values from the old array along with specified element at its correct position.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 
We can even do this in a single loop.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

2. System.arraycopy()

Above solution can be replaced with two calls to System.arraycopy(), which can efficiently copy an array from the specified source array, beginning at the specified position, to the specified position in the destination array.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

3. Using List

The idea is to convert the array into a list and call add() method on it which inserts the specified element at the specified position. Finally after inserting, we convert the list back to the array. This is illustrated below in Java 8 using Stream.

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

4. Java 8

In Java 8 and above, we can do something like:

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

5. Apache Commons

We can also leverage Apache Commons Lang ArrayUtils class which offers insert() method. It internally uses System.arraycopy() method.

 

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of