Array.copy()的使用
将 指定数组 复制成 指定大小的新数组,如果新数组长度大于指定数组,会用null或0填充。如果小于则截断指定数组
属于浅拷贝,只拷贝索引,不拷贝元素
-
源码
/** * *@param original 指定被复制的数组 * @param newLength 新数组的长度 * */ public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); }
-
使用
class Person{ int age; String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Test public void test(){ System.out.println("数值数组"); int[] arr1 = {1,2,3,4}; int[] arr2 = Arrays.copyOf(arr1,8); int[] arr3 = Arrays.copyOf(arr1,2); String x = ""; String y = ""; String z = ""; for (int i=0;i<Math.max(Math.max(arr1.length,arr2.length),arr3.length);i++){ if (i < arr1.length){ x += Integer.toString(arr1[i]); } if (i < arr2.length){ y += Integer.toString(arr2[i]); } if (i < arr3.length){ z += Integer.toString(arr3[i]); } } System.out.println("原数组 = " + x); System.out.println("比原数组大的复制数组 = " + y); System.out.println("比原数组小的复制数组 = " + z); System.out.println("字符数组"); String[] strArr = {"a","b","c","d"}; String[] strArr1 = Arrays.copyOf(strArr,8); String[] strArr2 = Arrays.copyOf(strArr,2); x = ""; y = ""; z = ""; for (int i=0;i<Math.max(Math.max(strArr.length,strArr1.length),strArr2.length);i++){ if (i < strArr.length){ x += strArr[i]; } if (i < strArr1.length){ y += strArr1[i]; } if (i < strArr2.length){ z += strArr2[i]; } } System.out.println("原数组 = " + x); System.out.println("比原数组大的复制数组 = " + y); System.out.println("比原数组小的复制数组 = " + z); // 证明浅拷贝 Person person1 = new Person(); person1.setAge(1); person1.setName("muci"); Person person2 = new Person(); person2.setAge(2); person2.setName("sc"); Person[] person = {person1,person2}; Person[] personCopy = Arrays.copyOf(person,2); System.out.println("personCopy[0].getAge() = " + personCopy[0].getAge()); person[0].setAge(3); System.out.println("personCopy[0].getAge() = " + personCopy[0].getAge()); }
# 输出结果 数值数组 原数组 = 1234 比原数组大的复制数组 = 12340000 比原数组小的复制数组 = 12 字符数组 原数组 = abcd 比原数组大的复制数组 = abcdnullnullnullnull 比原数组小的复制数组 = ab personCopy[0].getAge() = 1 personCopy[0].getAge() = 3