Java Arrays - copyOf() Method
The java.util.Arrays.copyOf() method is used to copy the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of the class newType.
Syntax
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
Here, U is the class of the objects in the original array and T is the class of the objects in the returned array.
Parameters
original |
Specify the array to be copied. |
newLength |
Specify the length of the copy to be returned. |
newType |
Specify the class of the copy to be returned. |
Return Value
Returns a copy of the original array, truncated or padded with nulls to obtain the specified length.
Exception
- Throws NegativeArraySizeException, if newLength is negative.
- Throws NullPointerException, if original is null.
- Throws ArrayStoreException, if an element copied from original is not of a runtime type that can be stored in an array of class newType.
Example:
In the example below, the java.util.Arrays.copyOf() method returns a copy of the given array, truncated or padded with nulls to obtain the specified length.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an Integer array Integer Arr1[] = {10, 5, 25}; //copy Arr1 into Arr2 with length 5 Number[] Arr2 = Arrays.copyOf(Arr1, 5, Number[].class); //printing Arr1 System.out.print("Arr1 contains:"); for(Integer i: Arr1) System.out.print(" " + i); //printing Arr2 System.out.print("\nArr2 contains:"); for(Number i: Arr2) System.out.print(" " + i); } }
The output of the above code will be:
Arr1 contains: 10 5 25 Arr2 contains: 10 5 25 null null
❮ Java.util - Arrays