java – 为什么Double.NaN在双重实例中包装时呢?

前端之家收集整理的这篇文章主要介绍了java – 为什么Double.NaN在双重实例中包装时呢?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
this question我学到了Double.NaN不等于自己.

我正在为自己验证这一点,并注意到,如果您将Double.NaN包含在双重实例中,情况并非如此.例如:

public class DoubleNaNTest {
    public static void main(String[] args) {
        double primitive = Double.NaN;
        Double object = new Double(primitive);

        // test 1 - is the primitive is equal to itself?
        boolean test1 = primitive == primitive;

        // test 2 - is the object equal to itself?
        boolean test2 = object.equals(object);

        // test 3 - is the double value of the object equal to itself?
        boolean test3 = object.doubleValue() == object.doubleValue();

        System.out.println("Test 1 = " + test1);
        System.out.println("Test 2 = " + test2);
        System.out.println("Test 3 = " + test3);
    }
}

输出

Test 1 = false
Test 2 = true
Test 3 = false

在我看来,所有三个测试都应该评估为false,因为所有三个操作都是等效的(如果你使用另一个Double.NaN之类的话).

有人可以解释这里发生了什么吗?

解决方法

发生的是等于方法故意偏离独立外部评价浮点.从Javadoc引用 java.lang.Double的equals(Object)方法.

However,there are two exceptions:

  • If d1 and d2 both represent Double.NaN,then the equals method
    returns true,even though
    Double.NaN==Double.NaN has the value
    false.
  • If d1 represents +0.0 while d2 represents -0.0,or vice versa,the
    equal test has the value false,even
    though +0.0==-0.0 has the value true.

This definition allows hash tables to
operate properly.

结果是,如果您想要100%的IEE浮点兼容性,则需要显式地取消对java.lang.Double实例进行解包,并比较生成的双精度值.

原文链接:https://www.f2er.com/java/124193.html

猜你在找的Java相关文章