集册 Java实例教程 复制指定的数组,截断或填充空值(如果需要),使副本具有指定的长度。

复制指定的数组,截断或填充空值(如果需要),使副本具有指定的长度。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

409
复制指定的数组,截断或填充空值(如果需要),使副本具有指定的长度。
// 来 自 n o w j a v a . c o m - 时代Java


//package com.nowjava;

import java.lang.reflect.Array;


public class Main {

    /**

     * 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 <tt>null</tt>.

     * Such indices will exist if and only if the specified length

     * is greater than that of the original array.

     * The resulting array is of exactly the same class as the original array.

     *

     * @param original  the array to be copied

     * @param newLength the length of the copy to be returned

     * @return a copy of the original array, truncated or padded with nulls

     * to obtain the specified length

     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative

     * @throws NullPointerException       if <tt>original</tt> is null

     * @since 1.6

     */


    @SuppressWarnings({ "unchecked", "varargs" })

    public static <T> T[] copyOf(T[] original, int newLength) {

        return (T[]) copyOf(original, newLength, original.getClass());

    }


    /**

     * 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 <tt>null</tt>.

     * 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 <tt>newType</tt>.

     *

     * @param original  the array to be copied

     * @param newLength the length of the copy to be returned

     * @param newType   the class of the copy to be returned

     * @return a copy of the original array, truncated or padded with nulls

     * to obtain the specified length

     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative

     * @throws NullPointerException       if <tt>original</tt> is null

     * @throws ArrayStoreException        if an element copied from

     *                                    <tt>original</tt> is not of a runtime type that can be stored in

     *                                    an array of class <tt>newType</tt>

     * @since 1.6

     */


    @SuppressWarnings({ "unchecked", "varargs" })

    public static <T, U> T[] copyOf(U[] original, int newLength,

           
展开阅读全文