4

在这段代码(story * 2) == tailTrue

并且false对于distance + 1 != tail.

==检查参考,因为 Long 是不可变的,对于两个不同的对象,它将为假,

这里的值story * 2在引用中变得相等tail,但它们是两个不同的对象,而不是用于池的编译时间常数。

   public class Test2 
{
         public static void main(String [] args) {

              Long tail = 2000L;
              Long distance = 1999L;
              Long story = 1000L;

                  System.out.println(tail > distance);

                  System.out.println((story * 2) == tail);

              if((tail > distance) ^ ((story * 2) == tail))
                  System.out.print("1");

              System.out.println(distance + 1 != tail);
              System.out.println((story * 2) == distance);

              if((distance + 1 != tail) ^ ((story * 2) == distance))
              System.out.print("2");

}

我检查了here,但对此没有任何解释。

4

3 回答 3

7

当您对包装的基元(例如Long)执行算术运算时,它们会自动拆箱为原始基元(例如long)。

考虑以下:

(story * 2) == tail

首先,story自动拆箱成 a long,并乘以 2。为了将结果longLong右侧的结果进行比较,后者也是自动拆箱的。

这里没有参考文献的比较。

下面的代码演示了这一点:

public static void main(String[] args) {
    Long tail = 2000L;
    Long story = 1000L;
    System.out.println((story * 2) == tail);          // prints true
    System.out.println(new Long(story * 2) == tail);  // prints false
}
于 2013-06-24T05:48:37.873 回答
4

我相信这是由于自动拆箱(故事 * 2)导致原始值 2000L。当你将它与也持有 2000L 值的尾部进行比较时,结果是正确的。当一项是原始项目时,请在此处检查 x==y 规则。

在此处输入图像描述

来源:http ://www.javapractices.com/topic/TopicAction.do?Id=197

于 2013-06-24T05:49:39.513 回答
0

乘法,加法和其他操作只能在基元上执行......

当您执行这些操作时,所有装箱的基元都将被拆箱并被视为基元类型。

所以在你的例子中 == 是检查长相等而不是对象相等。

于 2013-06-24T05:49:56.800 回答