[英]Autoboxing/Unboxing while casting Integer to int using 'cast' method
[英]Unboxing int value using Integer Class
在這種情況下,前兩個語句后變量y
的值是多少? 我假設它是整數7但是我的書說只有關系運算符<>“才會automatic unboxing
。我有點困惑變量Integer y
得到它的值。在newInteger(x)
是否有任何unboxing
?
Integer x = 7;
Integer y = new Integer(x);
println( "x == y" + " is " + (x == y))
當編譯器確定您希望比較值時,會發生拆箱。 使用==
可以比較Objects
,因此給出false
因為==
是對象之間的有效操作。 使用<
和>
沒有Object < OtherObject
概念,因此可以肯定你的意思是數字。
public void test() {
Integer x = 7;
Integer y = new Integer(x) + 1;
System.out.println("x == y" + " is " + (x == y));
System.out.println("x.intValue() == y.intValue()" + " is " + (x.intValue() == y.intValue()));
System.out.println("x < y" + " is " + (x < y));
System.out.println("x.intValue() < y.intValue()" + " is " + (x.intValue() < y.intValue()));
}
x == y是假的
x.intValue()== y.intValue()為true
x <y是真的
x.intValue()<y.intValue()為true
在這種情況下,前兩個語句后變量y的值是多少?
變量y
的值是對包含值7的Integer對象的引用 。
Integer x = 7;
在這種情況下, int
literal 7會自動裝入Integer
變量x
。
Integer y = new Integer(x);
這涉及將Integer
變量x
自動拆箱為int
(臨時)變量,該變量將傳遞給Integer
構造函數。 換句話說,它相當於:
Integer y = new Integer(x.intValue());
在此語句之后, y
指向一個與x
不同但包含相同int
包裝值的新對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.