How to add new elements to an array in Java?
To add new elements to an array in Java, you have a few options: If you know the size of the array in advance and the array is not full, you can simply assign a new value to an unused element in the array.
To add new elements to an array in Java, you have a few options:
- If you know the size of the array in advance and the array is not full, you can simply assign a new value to an unused element in the array. For example:
int[] array = new int[10];
array[0] = 1;
array[1] = 2;
array[2] = 3;This creates an array with three elements: 1, 2, and 3.
- If you need to add an element to the end of the array and you don't know the current size of the array, you can use a
Listinstead. The ArrayList class is a resizable array that allows you to add and remove elements as needed. Here's an example:
import java.util.List;
import java.util.ArrayList;
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);This creates a list with three elements: 1, 2, and 3.
- If you need to resize an existing array to add elements, you can use
Arrays.copyOf()to create a new array with the desired size and automatically copy the old elements. Here's an example:
import java.util.Arrays;
int[] array = {1, 2, 3};
array = Arrays.copyOf(array, array.length + 1);
array[array.length - 1] = 4;This creates a new array with four elements: 1, 2, 3, and 4.
Note that once you create an array, its size cannot be changed. If you frequently need to add or remove elements, consider using ArrayList instead.