Java.util.Arrays.copyOf() Method

Advertisements


Description

The java.util.Arrays.copyOf(U[] original, int newLength, Class<? extends T[]> newType) method copies 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.

Declaration

Following is the declaration for java.util.Arrays.copyOf(T,U) method

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)

Parameters

  • original -- This is the array to be copied.

  • newLength -- This is the length of the copy to be returned.

Return Value

This method returns a copy of the original array, truncated or padded with nulls to obtain the specified length.

Exception

  • NegativeArraySizeException -- If newLength is negative.

  • NullPointerException -- If original is null.

  • ArrayStoreException -- If an element copied from original is not of a runtime type that can be stored in an array of class newType

Example

The following example shows the usage of java.util.Arrays.copyOf(T,U) method.

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {

   public static void main(String[] args) {

      // initializing unsorted short array
      Short shortArr[] = new Short[]{5, 2, 15, 52, 10};

      // copy the array into another Number array
      Number[] arr2 = Arrays.copyOf(shortArr, 5, Number[].class);

      // let us print all the elements available in list
      System.out.println("The copied number array is:");
      for (Number number : arr2) {
         System.out.println("Number = " + number);
      }

   }
}

Let us compile and run the above program, this will produce the following result:

The copied number array is:
Number = 5
Number = 2
Number = 15
Number = 52
Number = 10



Advertisements
Advertisements