使用 Integer Class 拆箱 int 值

Unboxing int value using Integer Class

在这种情况下,前两个语句后变量 y 的值是多少?我假设它是整数 7 但我的书说对象的 automatic unboxing 只出现在关系运算符 < > 中。我有点困惑变量 Integer y 是如何获得它的价值的。是否有任何 unboxing 发生在 newInteger(x)

Integer x = 7;
Integer y = new Integer(x); 

println( "x == y" + " is " +  (x == y))
Integer x = 7;

在这种情况下,int 文字 7 自动装入 Integer 变量 x

Integer y = new Integer(x);

这涉及将 Integer 变量 x 自动拆箱为 int(临时)变量,然后传递给 Integer 构造函数。也就是说,相当于:

Integer y = new Integer(x.intValue());

在此语句之后,y 指向一个不同于 x 但包含相同 int 包装值的新对象。

当编译器确定您希望比较时,就会进行拆箱。使用 == 可以比较 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 is false

x.intValue() == y.intValue() is true

x < y is true

x.intValue() < y.intValue() is true


In this circumstance what is the value of variable y after the first two statements?

变量 y 的值是对包含值 7.

的 Integer 对象的 引用