Maz*_*zzy 2 java variables pass-by-reference
看看这段代码
Integer x = 5;
Integer y = 2;
Integer xy = x+y;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
x++;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
Run Code Online (Sandbox Code Playgroud)
如何在不使用为您计算代码的方法的情况下输出代码8?
一个Integer在Java中是不可变的.你不能改变它的价值.此外,它是一种特殊的自动装箱类型,可为int基元提供Object包装器.
例如,在您的代码中,x++不会修改引用的Integer对象x.它是联合国autoboxes到原始的int,后递增它,重新autoboxes它返回一个新Integer对象,并指定该Integer对x.
编辑以添加完整性: Autoboxing是Java中可能导致混淆的特殊事物之一.在谈论内存/对象时,幕后还有更多内容.该Integer类型还在自动装箱时实现飞重模式.缓存从-128到127的值.比较对象时应始终使用该.equals()方法Integer.
Integer x = 5;
Integer y = 5;
if (x == y) // == compares the *reference (pointer) value* not the contained int value
{
System.out.println("They point to the same object");
}
x = 500;
y = 500;
if (x != y)
{
System.out.println("They don't point to the same object");
if (x.equals(y)) // Compares the contained int value
{
System.out.println("But they have the same value!");
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅:为什么不在Java中缓存整数?了解更多信息(当然还有JLS)