Java – why double When Nan is packaged in a dual instance?

I learned double from this question Nan is not equal to yourself

I'm verifying this for myself and notice that if you put double Nan is included in dual instances, which is not the case For example:

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);
    }
}

Output:

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

In my opinion, all three tests should be evaluated as false because all three operations are equivalent (if you use another double. Nan or something)

Can anyone explain what happened here?

Solution

What happens is that the method deliberately deviates from the independent external evaluation Reference Java. From Javadoc Equals (object) method of lang. double

As a result, if you want 100% IEE floating-point compatibility, you need to explicitly cancel the Java Unpack the lang. double instance and compare the generated double value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>