与其他对象相似,当把一个数组引用变量赋给另一个变量时,只需修改一下该变量引用的对象即可.既没有生成数组的副本,也没有使一个数组的内容复制到另一个数组中.例如,考虑下面这个程序:
public static void main(String args[]) { int i; int nums1[] = new int[10]; int nums2[] = new int[10]; for(i=0;i<10;i++) { nums1[i] = i; } for(i=0;i<10;i++) { nums2[i] = -i; } System.out.println("Here is nums1:"); for(i=0;i<10;i++) System.out.print(nums1[i]+" "); System.out.println(""); System.out.println("Here is nums2:"); for(i=0;i<10;i++) System.out.print(nums2[i]+" "); System.out.println(""); nums2 = nums1; System.out.println("Here is nums2 after assignment:"); for(i=0;i<10;i++) System.out.print(nums2[i]+" "); System.out.println(""); nums2[3] = 99; System.out.println("Here is nums1 atfer change through nums2:"); for(i=0;i<10;i++) System.out.print(nums1[i]+" "); }
输出:
Here is nums1: 0 1 2 3 4 5 6 7 8 9 Here is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 Here is nums2 after assignment: 0 1 2 3 4 5 6 7 8 9 Here is nums1 atfer change through nums2: 0 1 2 99 4 5 6 7 8 9
正如输出所示,在把nums1赋值给nums2之后,两个数组引用变量都指向一个对象.(赋给nums2的是nums1的指针,而不是实参的副本)