Enlarging an Array in Java: Preserving Current Elements
Arrays in Java, unlike in other programming languages, are fixed in size. Adding new elements to a full array requires manual resizing or alternative data structures.
Resizing an Array
Due to Java's array immutability, resizing involves copying existing elements into a new array with the desired size. The java.lang.System.arraycopy(...) method can accomplish this task:
int[] oldArray = {1, 2, 3, 4, 5}; int[] newArray = new int[oldArray.length + 1]; // Larger array System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
Alternative Data Structures
Another option is to employ dynamic data structures like java.util.ArrayList
ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); // No resizing needed as the ArrayList expands dynamically
Using Arrays.copyOf(...)
Java 9 introduced the java.util.Arrays.copyOf(...) methods, which simplify array resizing:
int[] oldArray = {1, 2, 3, 4, 5}; int[] newArray = Arrays.copyOf(oldArray, oldArray.length + 1);
The above is the detailed content of How to Efficiently Enlarge Arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!