Home >Java >javaTutorial >How to Efficiently Enlarge Arrays in Java?

How to Efficiently Enlarge Arrays in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 07:52:11548browse

How to Efficiently Enlarge Arrays in Java?

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. Unlike arrays, ArrayLists can automatically enlarge themselves as elements are added:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn