简体   繁体   English

等于表达式中的 Integer 算术

[英]Integer arithmetic in equals expression

I know the first expression evaluates to false because these are two distinct Integer objects.我知道第一个表达式的计算结果为 false,因为它们是两个不同的Integer对象。

I'm not sure why the second expression evaluates to true.我不确定为什么第二个表达式的计算结果为真。

public static void main(String[] args)  {
   System.out.println(new Integer(1000)==new Integer(1000)); // false       
   System.out.println(new Integer(1000)==new Integer(1000)+new Integer(0)); // true
}

I suspect that the second expression evaluates to true because the right hand side first gets unboxed to an int and then gets compared to the left side.我怀疑第二个表达式的计算结果为 true,因为右侧首先被拆箱为int ,然后与左侧进行比较。 Is that true and if so, is this the defined behavior?这是真的吗?如果是这样,这是定义的行为吗?

Because new Integer(1000)+new Integer(0) return 1000 value.因为 new Integer(1000)+new Integer(0) 返回 1000 值。 So java compare values of Integer.所以 java 比较 Integer 的值。 1000==1000 is equals true. 1000==1000 等于真。 Bu first output is false because int this why java compare references of objects. Bu首先 output 是错误的,因为这就是为什么 java 比较对象的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM