0

我在 Java 中有一个充满数据的数组。我想知道的是,如果我做这样的事情:

int[] array = new int[2];
array[0] = 0;
array[1] = 1;

//other statements...

array[1] = array[0];

如果我array[1]再次更改值,值也会array[0]更改吗?谢谢!

4

1 回答 1

3

如果我再次更改 array[1] 的值,array[0] 的值也会更改吗?

不,此声明:

array[1] = array[0];

只需将第二个元素的值复制到第一个元素中。就好像你有两个独立的变量:

int x = 10;
int y = x;
// Further changes to x don't affect y

如果您一组引用,例如

StringBuilder[] builders = new StringBuilder[10];
builders[0] = new StringBuilder("Original");
builders[1] = builders[0];
builders[0] = new StringBuilder("Hello");
System.out.println(builders[1]); // Prints Original

最后一个赋值语句不会改变builders[1]... 的值,但是如果我们写了:

builders[0].append("Foo");
System.out.println(builders[1]); // Prints OriginalFoo

then the values of builders[0] and builders[1] haven't changed - they still refer to the same object - but the contents of that object have changed, hence the output in the final line.

于 2013-03-05T01:42:08.170 回答