比较Java中的双打给出了奇怪的结果

比较Java中的双打给出了奇怪的结果

本文介绍了比较Java中的双打给出了奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白为什么会发生以下情况:

I really can'get my head around why the following happens:

Double d = 0.0;
System.out.println(d == 0); // is true
System.out.println(d.equals(0)); // is false ?!

然而,这样可以预期:

Double d = 0.0;
System.out.println(d == 0.0); // true
System.out.println(d.equals(0.0)); // true

我很乐意这与autoboxing有关,但我真的很不知道为什么 0 会在使用 == 运算符时使用不同的方式,而 .equals 被称为

I'm positive that this is related to autoboxing in some way, but I really don't know why 0 would be boxed differently when the == operator is used and when .equals is called.

这不是隐含地违反了 code>合同?

Doesn't this implicitly violate the equals contract ?


  *  It is reflexive: for any non-null reference value
  *     x, x.equals(x) should return
  *     true.

编辑

感谢您的快速答案。我认为它是不同的盒子,真正的问题是:为什么是不同的盒子?我的意思是,如果 d == 0d d.equals(0d)更直观, ,但是如果 d == 0 看起来像一个整数 true than'intuitive' d.equals(0)也应该是真的。

Thanks for the fast answers. I figured that it is boxed differently, the real question is: why is it boxed differently ? I mean that this would be more intuitive if d == 0d than d.equals(0d) is intuitive and expected, however if d == 0 which looks like an Integer is true than 'intuitively' d.equals(0) should also be true.

推荐答案

只需将其更改为

System.out.println(d.equals(0d)); // is false ?! now true

您正在与 Integer 0

System.out.println(d.equals(0)); // is false ?!

0 将自动装箱至整数,并且Integer的一个实例将被传递给 equals()方法 Double 类,它将像

0 will be autoboxed to Integer and an instance of Integer will be passed to equals() method of Double class, where it will compare like

@Override
    public boolean equals(Object object) {
        return (object == this)
                || (object instanceof Double)
                && (doubleToLongBits(this.value) == doubleToLongBits(((Double) object).value));
    }

当然会返回 false

当您使用 = = 它比较值,所以不需要autobox,它直接对值进行操作。其中 equals()接受 Object 所以如果你尝试调用 d1.equals(0) 0 不是Object,所以它将执行自动装箱,它将它打包成一个对象的整数。

when you do comparison using == it compares values so there is no need to autobox , it directly operates on value. Where equals() accepts Object so if you try to invoke d1.equals(0) , 0 is not Object so it will perform autoboxing and it will pack it to Integer which is an Object.

这篇关于比较Java中的双打给出了奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:23