在这种情况下,变量y在前两条语句之后的值是多少?我假设它是Integer 7,但是我的书说对象的automatic unboxing只发生在关系运算符< >“。我有点困惑变量Integer y是如何得到它的值的。unboxing在newInteger(x)中出现吗?
Integer x = 7;
Integer y = new Integer(x);
println( "x == y" + " is " + (x == y))发布于 2015-07-13 10:30:48
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包装值的新对象。
发布于 2015-07-13 10:37:50
当编译器是(希望比较值的特定)时,就会取消装箱。使用==可以比较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()为真 Xx.intValue() < y.intValue()为真
在这种情况下,变量y在前两个语句之后的值是多少?
变量y的值是对包含值7的整数对象的引用。
https://stackoverflow.com/questions/31380878
复制相似问题