java – 为什么Double.NaN在双重实例中包装时呢?
发布时间:2020-12-14 17:41:19 所属栏目:Java 来源:网络整理
导读:从 this question我学到了Double.NaN不等于自己. 我正在为自己验证这一点,并注意到,如果您将Double.NaN包含在双重实例中,情况并非如此.例如: public class DoubleNaNTest { public static void main(String[] args) { double primitive = Double.NaN; Doubl
从
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)方法.
结果是,如果您想要100%的IEE浮点兼容性,则需要显式地取消对java.lang.Double实例进行解包,并比较生成的双精度值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |