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]
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024