[英]Java, how to 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
如何在不使用為您計算代碼的方法的情況下輸出代碼8?
Java中的Integer
是不可變的 。 你不能改變它的價值。 此外,它是一種特殊的自動裝箱類型,可為int
原語提供Object包裝器。
例如,在您的代碼中, x++
不會修改x
引用的Integer
對象。 它將它自動解壓縮到原始int
,后遞增它,重新自動執行它返回一個新的Integer
對象並將該Integer
分配給x
。
編輯以添加完整性: Autoboxing是Java中可能導致混淆的特殊事物之一。 在談論內存/對象時,幕后還有更多內容。 Integer
類型還在自動裝箱時實現flyweight模式。 緩存從-128到127的值。 在比較Integer
對象時,應始終使用.equals()
方法。
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!");
}
}
請參閱: 為什么不在Java中緩存整數? 了解更多信息(當然還有JLS)
修改x
后需要更新xy
。 所以:
x++;
xy = x + y;
xy2 = x + y;
在Java中,如果希望更改值,則需要自己更新變量。 它與其他表達兩個變量之間關系的語言不同,只要變量發生變化,就會保持這種關系。
表達式:xy = x + y並不意味着現在xy取決於x和y的值(如果它們改變了,xy也改變了)。 您可以看到如下:表達式x + y的值插入到xy中。
因此,在設置xy的值之前,必須增加x的值(x ++)。
我是java的新手,我不太確定這個問題的上下文,但是如果你想做的只是輸出8,你可以把它變成xy ++而不是x ++。
Integer x = 5;
Integer y = 2;
Integer xy = x+y;
int xy2 = x+y; // just testing to see if it makes a difference
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
**xy++;**
System.out.println("xy = " + xy); // **outputs: 8**
System.out.println("xy2 = " + xy2); // outputs: 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.