Appearance
add an element to int [] array in java
To add an element to an array in Java, you can use one of the following methods:
- Use
Arrays.copyOf()(Recommended):
java
import java.util.Arrays;
int[] original = {1, 2, 3};
int[] result = Arrays.copyOf(original, original.length + 1);
result[result.length - 1] = 4;This method creates a new array that is one element larger than the original, copies the existing elements, and leaves the last slot available for the new value.
- Use an ArrayList:
java
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Arrays;
int[] original = {1, 2, 3};
List<Integer> list = Arrays.stream(original).boxed().collect(Collectors.toList());
list.add(4);
int[] result = list.stream().mapToInt(i -> i).toArray();This method converts the array to an ArrayList, adds the new element to the list, and then converts the list back to an array using the stream and mapToInt methods introduced in Java 8.
Keep in mind that Java arrays have a fixed size, so both methods above create a new array. The original array reference remains unchanged. To update the original variable, simply reassign it:
java
import java.util.Arrays;
int[] original = {1, 2, 3};
original = Arrays.copyOf(original, original.length + 1);
original[original.length - 1] = 4;