数组拷贝原理
在使用Arrays工具类的过程中,经常会使用到copyOf()的方法,那么底层究竟如何实现的呢?我们看一下。
最通用的方法源码
/**
* 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 <U> 源数组的类
* @param <T> 返回的数组的类
* @param original 需要复制的源数组
* @param newLength 新数组的长度
* @param newType 返回的数组的类型
* @return 返回指定长度的,源数组的副本,newLength>original .length,则多余的部分使用 nulls
* @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
*/
public static <T,U> T[] copyOf(U[] original, int newLength, Class<