1. /**
    2. * Copies the specified array, truncating or padding with nulls (if necessary) //~ 1. 切断或用 null 填充以保证长度为 newLength
    3. * so the copy has the specified length. For all indices that are
    4. * valid in both the original array and the copy, the two arrays will
    5. * contain identical values. For any indices that are valid in the
    6. * copy but not the original, the copy will contain <tt>null</tt>.
    7. * Such indices will exist if and only if the specified length
    8. * is greater than that of the original array.
    9. * The resulting array is of the class <tt>newType</tt>. //~ 2. 返回 newType 类型的数组
    10. *
    11. * @param <U> the class of the objects in the original array
    12. * @param <T> the class of the objects in the returned array
    13. * @param original the array to be copied
    14. * @param newLength the length of the copy to be returned
    15. * @param newType the class of the copy to be returned
    16. * @return a copy of the original array, truncated or padded with nulls
    17. * to obtain the specified length
    18. * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
    19. * @throws NullPointerException if <tt>original</tt> is null
    20. * @throws ArrayStoreException if an element copied from
    21. * <tt>original</tt> is not of a runtime type that can be stored in
    22. * an array of class <tt>newType</tt>
    23. * @since 1.6
    24. */
    25. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    26. @SuppressWarnings("unchecked")
    27. T[] copy = ((Object)newType == (Object)Object[].class)
    28. ? (T[]) new Object[newLength]
    29. : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    30. System.arraycopy(original, 0, copy, 0,
    31. Math.min(original.length, newLength));
    32. return copy;
    33. }

    此方法返回一个新的数组, 长度为 newLength, 如果新的长度比原来的长, 则会填充 null(基本数据类型填充默认值).

    此方法是浅拷贝, 根本使用的还是 System.arraycopy(), 而 System.arraycopy() 本身也是浅拷贝.