Arrays.copyOf() 用法:
Arrays的copyOf()方法传回的数组是新的数组对象,改变传回数组中的元素值,不会影响原来的数组。
copyOf()的第二个自变量指定要建立的新数组长度,如果新数组的长度超过原数组的长度,则保留数组默认值,例如:
代码块:
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1, 5);
int[] arr3 = Arrays.copyOf(arr1, 10);
for(int i = 0; i < arr2.length; i++)
System.out.print(arr2[i] + " ");
System.out.println();
for(int i = 0; i < arr3.length; i++)
System.out.print(arr3[i] + " ");
}
}
运行结果:
1 2 3 4 5
1 2 3 4 5 0 0 0 0 0
Two:
/** * @Description 复制指定的数组, 如有必要用 null 截取或填充,以使副本具有指定的长度 *
对于所有在原数组和副本中都有效的索引,这两个数组相同索引处将包含相同的值 * 对于在副本中有效而在原数组无效的所有索引,副本将填充
null,当且仅当指定长度大于原数组的长度时,这些索引存在 * 返回的数组属于 newType 类 * @param
original 要复制的数组 * @param newLength 副本的长度 * @param newType 副本的类 *
@return T 原数组的副本,截取或用 null 填充以获得指定的长度 * @throws NegativeArraySizeException 如果 newLength 为负 * @throws
NullPointerException 如果 original 为 null * @throws ArrayStoreException
如果从 original 中复制的元素不属于存储在 newType 类数组中的运行时类型@since 1.6 */ public static <T,U> T[] copyOf(U[] original, int
newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy; }
从代码可知,数组拷贝时调用的是本地方法 System.arraycopy() ;
Arrays.copyOf()方法返回的数组是新的数组对象,原数组对象仍是原数组对象,不变,该拷贝不会影响原来的数组。
System.arraycopy() 源码如下:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
参数说明:
src:源对象
srcPos:源数组中的起始位置
dest:目标数组对象
destPos:目标数据中的起始位置
length:要拷贝的数组元素的数量
总结:Arrays.copyOf()方法返回的数组是新的数组对象,原数组对象仍是原数组对象,不变,该拷贝不会影响原来的数组。