创建后数组大小更改

任何人都可以解释这里发生的事情。 我的印象是,一旦创建并声明了数组的大小,就无法更改。

public class ArrayManipulation { public static void main(String[] args) { int a[] = {1, 2, 3};//new int[3]; int b[] = new int[a.length-1]; System.out.print("a = "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); for (int i = 0; i < b.length; i++) b[i] = a[i]; //This is the bit I am confused about.. I was expecting an error here a = b; System.out.print("a = "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } } 

数组是对象,是的,一旦它们被创建,它们的大小就不会改变。

在线:

 a= b; 

你指向b对象a引用。 所以你引用的初始对象仍然在VM中,直到它被垃圾收集。

但是你的数组大小没有改变,但你引用的是指向一个不同的数组/对象

ab都是int[]类型。 所以a = b只需将a = b的值赋给a = b的值。

在此赋值之后, ab引用相同的数组,并且b引用的初始数组可以由垃圾收集器收集,因为它不再被访问。

当您说a = b时,您正在更改指向的引用。

由于数组是对象,因此设置一个等于另一个会更改引用。 两个数组仍然存在,但两个引用 – ab – 都指向b的位置。 实际删除数组a的唯一方法是垃圾收集它。

你实际上并没有改变数组大小,它看起来就像它。

  //This is the bit I am confused about.. I was expecting an error here a = b; 

是的,你对正确的事感到困惑! ab为自己分配了自己的内存。 使用a = b您将指向为b分配的内存。

也许将这些额外的sysout添加到代码中会有所帮助,请参阅输出:

 public class ArrayManipulation { public static void main(String[] args) { int a[] = {1, 2, 3};//new int[3]; int b[] = new int[a.length-1]; System.out.print("a = "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); for (int i = 0; i < b.length; i++) b[i] = a[i]; System.out.print("NEW -- before a=b. a = " + a); System.out.print("NEW -- before a=b. b = " + b); //This is the bit I am confused about.. I was expecting an error here a = b; System.out.print("NEW -- after a=b. a = " + a); System.out.print("NEW -- after a=b. b = " + b); System.out.print("a = "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } }