簡體   English   中英

使用Integer Class拆箱int值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM