Java object assignment behaviour not consistent?

别来无恙 提交于 2020-01-17 04:39:42

问题


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:

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 

回答1:


The behavior is consistent. This line:

x += 23;

actually assigns a different Integer object to x; it does not modify the value represented by x before that statement (which was, in fact, identical to object y). Behind the scenes, the compiler is unboxing x and then boxing the result of adding 23, as if the code were written:

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).

What's going on in the second piece is that this line:

x[0] += 10;

also assigns a new object to x[0]. But since x and y refer to the same array, this also changes y[0] to be the new object.




回答2:


Integer is immutable, so you cannot modify its state once created. 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.

Arrays, on the other hand, are mutable, so when you change the state of the array e.g. changing one of the elements in the array, the other is affected as well.




回答3:


When you do this x += 23;, you actually create another object, and you made x point on this new object. Therefore, x and y are 2 different objects.



来源:https://stackoverflow.com/questions/26789940/java-object-assignment-behaviour-not-consistent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!