![]() |
VOOZH | about |
Arrays.copyOf() is a method of java.util.Arrays class. It is used to copy the specified array, truncating or padding with false (for boolean arrays) if necessary so that the copy has the specified length.
This method can be used with both 1D and 2D arrays, but it’s important to note that Arrays.copyOf() performs a shallow copy, meaning that if you’re copying an array of objects, the objects themselves are not duplicated—only the references to them.
The below example shows the basic use of Arrays.copyOf() method to create a copy of an array with a specified length.
Original Array: [1, 2, 3, 4, 5] Copied Array: [1, 2, 3, 4, 5]
This demonstrates how Arrays.copyOf() method can be used to duplicate a 1D array with basic functionality before exploring complex examples.
Table of Content
Here, we will learn how to use Arrays.copyOf() method to copy a 1D array and then modify its extra elements.
Arrays.copyOf(int [] original, int newLength);
Original Array: 1 2 3 Copied array after modifications: 1 2 3 4 5
When the length of the copied array is greater than the original, the new array is padded with default values (0 for int, false for boolean, and null for reference types) to fill the remaining indices.
Example:
Original Array: 1 2 3 New array of higher length: 1 2 3 0 0
When working with 2D arrays, the Arrays.copyOf() method performs a shallow copy, meaning only the references to each row are copied. For a deep copy of the rows in a 2D array, you would need to copy each row individually.
Arrays.copyOf(originalArray, newLength);
Original Array: [1, 2, 3] [4, 5, 6] [7, 8, 9] Copied Array: [1, 2, 3] [4, 5, 6] [7, 8, 9]