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 a temporary array:
int[] original = {1, 2, 3};
int[] result = new int[original.length + 1];
System.arraycopy(original, 0, result, 0, original.length);
result[result.length - 1] = 4;
This method creates a new array that is one element larger than the original array, copies the elements from the original array to the new array, and then adds the new element to the end of the new array.
- Use an ArrayList:
int[] original = {1, 2, 3};
List<Integer> list = new ArrayList<>(original.length + 1);
for (int i : original) {
list.add(i);
}
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 both of these methods create a new array, so the original array remains unchanged. If you want to modify the original array, you can use the first method and assign the result back to the original array:
int[] original = {1, 2, 3};
int[] result = new int[original.length + 1];
System.arraycopy(original, 0, result, 0, original.length);
result[result.length - 1] = 4;
original = result;
Alternatively, you can use an ArrayList and the set
method to modify the original array:
int[] original = {1, 2, 3};
List<Integer> list = IntStream.of(original).boxed().collect(Collectors.toList());
list.add(4);
IntStream.range(0, list.size()).forEach(i -> original[i] = list.get(i));
This method converts the array to an ArrayList, adds the new element to the list, and then copies the elements from the list back to the array using the IntStream.range
and forEach
methods introduced in Java 8.