Arrays.copyOf()
Copies an array into a new one of the same or another length. copyOfRange() copies a part.
Available since: Java 6
Syntax
static int[] copyOf(int[] original, int newLength)Parameters
| Parameter | Type | Description |
|---|---|---|
| original | int[], T[], … | The source array. |
| newLength | int | The length of the copy. If longer, the tail is filled with default values; if shorter, the rest is cut off. |
Return value
same array typeA new array of the same type.
Examples
A copy, a longer copy and a part of an array:
void main() {
int[] original = {1, 2, 3};
int[] copy = Arrays.copyOf(original, original.length);
int[] bigger = Arrays.copyOf(original, 5);
int[] middle = Arrays.copyOfRange(new int[] {10, 20, 30, 40}, 1, 3);
copy[0] = 99;
IO.println(Arrays.toString(original));
IO.println(Arrays.toString(copy));
IO.println(Arrays.toString(bigger));
IO.println(Arrays.toString(middle));
}Output:
[1, 2, 3]
[99, 2, 3]
[1, 2, 3, 0, 0]
[20, 30]Notes
The assignment int[] b = a; does not copy the array — both variables point to the same array. A copy is made with copyOf() or a.clone(). The copy is shallow: for an array of objects the references are copied and the objects themselves are shared.
See also
- Arrays.fill() — Fills the whole array or part of it with one value.
- Arrays.equals() — Compares the contents of two arrays element by element.
- array.length — The length of an array — the number of elements. A field, not a method: no parentheses.
Related recipes
In the tutorial
- The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.