Arrays.copyOf方法

所见即所得,走起:

1.基本数据类型

private static void copyP() {
		int [] arr  = {1,2,3,4};
		int[] copyOf1 = Arrays.copyOf(arr, 2);
		int[] copyOf2 = Arrays.copyOf(arr, 4);
		int[] copyOf3 = Arrays.copyOf(arr, 6);
		System.out.println(Arrays.toString(copyOf1));
		System.out.println(Arrays.toString(copyOf2));
		System.out.println(Arrays.toString(copyOf3));
	}

打印结果:

[1, 2]
[1, 2, 3, 4]
[1, 2, 3, 4, 0, 0]

 

2.引用数据类型

private static void copyNotP() {
		MyClass [] arr  = {new MyClass(),new MyClass(),new MyClass(),new MyClass()};
		MyClass[] copyOf1 = Arrays.copyOf(arr, 2);
		MyClass[] copyOf2 = Arrays.copyOf(arr, 4);
		MyClass[] copyOf3 = Arrays.copyOf(arr, 6);
		System.out.println(Arrays.toString(copyOf1));
		System.out.println(Arrays.toString(copyOf2));
		System.out.println(Arrays.toString(copyOf3));
		
	}

打印结果:

[MyClass@15db9742, MyClass@6d06d69c]
[MyClass@15db9742, MyClass@6d06d69c, MyClass@7852e922, MyClass@4e25154f]
[MyClass@15db9742, MyClass@6d06d69c, MyClass@7852e922, MyClass@4e25154f, null, null]

结论:

将原数组拷贝一定长度到新数组,如果长度过长,会给出初始值占位.

你可能感兴趣的:(#,JAVA源码阅读,#,JAVA基础)