This post will discuss how to add an element to a specific position in an array in Java.

1. Using System.arraycopy() method

We can use the System.arraycopy() method to copy elements from one array to another. This method can efficiently copy an array from the specified source array, beginning at the specified position, to the specified position in the destination array. We can use this method to create a new array with one more element and copy the elements from the original array to the new array, leaving a space for the element to be inserted at the specified index. This method is demonstrated below:

Download  Run Code

2. Using a loop

Instead of calling the System.arraycopy() method, we can write our own custom routine to shift the elements in the array to the right by one position from the specified index. The idea is to declare a new array with one more element to have an extra space in the array to accommodate the new element. Then we can use a for loop to iterate over the array from right to left and assign each element to the next position until we reach the specified index. Then we can assign the element to be inserted at that index. Here’s a working code that is logically the same as the System.arraycopy() method:

Download  Run Code

3. Using Apache Commons Lang Library

Another option to add an element to a specific position in an array in Java is to use the Apache Commons Lang library, which provides the ArrayUtils class with various utility methods for working with arrays. The ArrayUtils class has a method called insert() that can insert an element or multiple elements into an array at the given index. This method is overloaded for all primitive types and object arrays. The insert() method returns a new array with the inserted element(s), and does not modify the original array. Here is an example of how to use this method:

Download Code

4. Using a List

We can also use a List instead of an array to add elements into an array at the given index. A List is a collection that allows dynamic resizing and insertion of elements at any position. We can use the add() method to insert an element at the specified index in a List. We can also convert a primitive array to a List and vice versa using the Stream API. Here’s an example of this approach:

Download  Run Code

That’s all about adding an element to a specific position in an array in Java.