System.arraycopy()
Copies part of one array into another (or the same) array.
Available since: Java 1.0
Syntax
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)Parameters
| Parameter | Type | Description |
|---|---|---|
| src | Object | The source array. |
| srcPos | int | The start index in the source array. |
| dest | Object | The destination array. |
| destPos | int | The index where the first copied element goes. |
| length | int | How many elements to copy. |
Examples
Copying three elements from the middle of an array:
void main() {
int[] source = {10, 20, 30, 40, 50};
int[] target = new int[5];
System.arraycopy(source, 1, target, 0, 3);
IO.println(Arrays.toString(target));
}Output:
[20, 30, 40, 0, 0]Shifting inside one array to make room for an insert:
void main() {
int[] data = {1, 2, 4, 5, 0};
System.arraycopy(data, 2, data, 3, 2);
data[2] = 3;
IO.println(Arrays.toString(data));
}Output:
[1, 2, 3, 4, 5]Going past the end of an array:
void main() {
int[] small = {1, 2, 3};
System.arraycopy(small, 1, new int[10], 0, 5);
}Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: arraycopy: last source index 6 out of bounds for int[3]Notes
The method creates nothing: the destination must exist and be big enough. Overlapping regions of the same array are copied correctly. If you need a new array, Arrays.copyOf() or Arrays.copyOfRange() are simpler — they create an array of the right length themselves. The element types must match, otherwise you get ArrayStoreException.
See also
- Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.
- Arrays.fill() — Fills the whole array or part of it with one value.
- array.length — The length of an array — the number of elements. A field, not a method: no parentheses.
In the tutorial
- The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.