简体   繁体   English

Java对象分配行为不一致?

[英]Java object assignment behaviour not consistent?

According to this answer https://stackoverflow.com/a/12020435/562222 , assigning an object to another is just copying references, but let's see this code snippet: 根据这个答案https://stackoverflow.com/a/12020435/562222 ,将对象分配给另一个对象只是复制引用,但让我们看一下下面的代码片段:

public class TestJava {

    public static void main(String[] args) throws IOException {

        {
            Integer x;
            Integer y = 223432;
            x = y;
            x += 23;
            System.out.println(x);
            System.out.println(y);
        }
        {
            Integer[] x;
            Integer[] y = {1,2, 3, 4, 5};
            x = y;
            x[0] += 10;
            printArray(x);
            printArray(y);
        }
    }

    public static <T> void printArray(T[] inputArray) {
        for(T element : inputArray) {
            System.out.printf("%s ", element);
        }
        System.out.println();
    }

}

Running it gives: 运行它可以得到:

223455
223432
11 2 3 4 5 
11 2 3 4 5 

The behavior is consistent. 行为是一致的。 This line: 这行:

x += 23;

actually assigns a different Integer object to x ; 实际上为x分配了一个不同的Integer对象; it does not modify the value represented by x before that statement (which was, in fact, identical to object y ). 它不会修改该语句之前的x表示的值(实际上与对象y相同)。 Behind the scenes, the compiler is unboxing x and then boxing the result of adding 23, as if the code were written: 在幕后,编译器将x拆箱,然后将加23的结果装箱,就像编写代码一样:

x = Integer.valueOf(x.intValue() + 23);

You can see exactly this if you examine the bytecode that is generated when you compile (just run javap -c TestJava after compiling). 如果检查编译时生成的字节码(在编译后仅运行javap -c TestJava ),就可以确切地看到这一点。

What's going on in the second piece is that this line: 第二部分中的内容是这一行:

x[0] += 10;

also assigns a new object to x[0] . 还为x[0]分配了一个新对象。 But since x and y refer to the same array, this also changes y[0] to be the new object. 但是由于xy引用相同的数组,因此这也将y[0]更改为新对象。

Integer is immutable, so you cannot modify its state once created. Integer是不可变的,因此一旦创建,便无法修改其状态。 When you do this: 执行此操作时:

Integer x;
Integer y = 223432;
x = y;
x += 23;

The line x += 23 is assigning a new Integer value to x variable. x += 23行将新的Integer值分配给x变量。

Arrays, on the other hand, are mutable, so when you change the state of the array eg changing one of the elements in the array, the other is affected as well. 另一方面,数组是可变的,因此当您更改数组的状态(例如,更改数组中的一个元素)时,另一个也会受到影响

When you do this x += 23; 当你这样做x += 23; , you actually create another object, and you made x point on this new object. ,您实际上创建了另一个对象,并在此新对象上使x指向了x。 Therefore, x and y are 2 different objects. 因此,x和y是2个不同的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM