//基础类型 int n1 = 10; int n2 = n1; n2=80; System.out.println("n1="+n1); System.out.println("n2="+n2); //数组 int[] arr1 = {10,20,30}; int arr2[] = arr1; arr2[0]= 40; System.out.println(Arrays.toString(arr1)); System.out.println(Arrays.toString(arr2));
输出结果:
n1=10
n2=80
[40, 20, 30]
[40, 20, 30]
将一个数组赋给另一个数组的时候是赋予地址,就相当于arr1和arr2现在是同一个地址,改变arr2中的值也会影响arr1的值;
int[] arr3=new int[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr3[i] = arr1[i]; } arr3[0] = 60; System.out.println(Arrays.toString(arr1)); System.out.println(Arrays.toString(arr3));
输出结果:
[10, 20, 30]
[60, 20, 30]
重新拷贝一个和arr1相同长度的新数组arr3,就相当于重新给arr3找了一个新地址,改变arr3中的值不会影响arr1的值;
还有一个注意点:输出数组的时候要转成字符串;