为什么 5.0 == 5L return me a true?

Why does 5.0 == 5L return me a true?

System.out.println(" answer is " + (5.0==5L));

这个returns true! 它应该 return 一个 false 值,因为正在比较两种不同的类型。 即使 doublelong 值进行比较!

比较longs和doubles时,long被提升为double,然后比较两者。因为两者都等于五,所以结果是 true.

两个操作数正在按照JLS section 5.6.2进行二进制数字提升,以便为两个操作数获得单一类型。

规则是这样的:

  • If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
  • Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
    • If either operand is of type double, the other is converted to double.
    • ...
  • ...

您的第二个操作数是 double 类型,因此 long 值隐式转换为 double,然后比较两个 double 值 - 并且它们'重新平等。

它 returns 正确,因为它正在比较两种类型的 "primitive variables"。如果它们是相同的值,它就有效。

相比之下,在 "object variables" returns 上使用“==” 如果引用指向同一对象则为真,例如

Object a = new Object();  
Object b = a;
//then a==b is true

但是:

Object a = new Object();
Object b = new Object();
//then a==b is false