本文介绍了Java对象分配行为不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此答案 https://stackoverflow.com/a/12020435/562222 ,将一个对象分配给另一个对象只是复制参考,但让我们看一下以下代码片段:

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();
    }

}

运行它会给出:

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

推荐答案

行为是一致的.这行:

x += 23;

实际上为x分配了一个不同的Integer对象;它不会修改该语句之前的x表示的值(实际上与对象y相同).在后台,编译器将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);

如果您检查编译时生成的字节码(在编译后只需运行javap -c TestJava),就可以确切地看到这一点.

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;

还将一个新对象分配给x[0].但是,由于xy引用相同的数组,因此这也会将y[0]更改为新对象.

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.

这篇关于Java对象分配行为不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 22:00