Java签名零和拳击 [英] Java signed zero and boxing

查看:108
本文介绍了Java签名零和拳击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我用Java编写了一个项目,并注意到双重/双重实现的一个非常奇怪的功能。 Java中的double类型有两个0,即0.0和-0.0(有符号零)。奇怪的是:

  0.0 == -0.0 

评估为 true ,但:

  new Double(0.0).equals(new Double(-0.0))

评估为 false 。有人知道这个原因吗?

解决方案

这一切都在 javadoc


请注意,在大多数情况下,对于Double,d1和d2类的两个实例,d1.equals(d2)的值为true,如果且仅当

  d1.doubleValue()== d2.doubleValue()

也有值true。但是,有两个例外:




  • 如果d1和d2都表示Double.NaN,则equals方法返回true,即使Double。 NaN == Double.NaN的值为false。

  • 如果d1表示+0.0,而d2表示-0.0,反之亦然,则相等的测试值为false,即使+0.0 == - 0.0的值为true



此定义允许哈希表正常运行。 >






现在你可能会问为什么 0.0 == -0.0 是真的。实际上它们并不完全相同。例如:

  Double.doubleToRawLongBits(0.0)== Double.doubleToRawLongBits(-0.0); // false 

是false。但是, JLS 要求(符合IEEE 754标准的规则):


正零和负零被认为是相等的。


因此 0.0 == -0.0 是true。


Lately I've written a project in Java and noticed a very strange feature with double/Double implementation. The double type in Java has two 0's, i.e. 0.0 and -0.0 (signed zero's). The strange thing is that:

0.0 == -0.0

evaluates to true, but:

new Double(0.0).equals(new Double(-0.0))

evaluates to false. Does anyone know the reason behind this?

解决方案

It is all explained in the javadoc:

Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if

   d1.doubleValue() == d2.doubleValue() 

also has the value true. 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.


Now you might ask why 0.0 == -0.0 is true. In fact they are not strictly identical. For example:

Double.doubleToRawLongBits(0.0) == Double.doubleToRawLongBits(-0.0); //false

is false. However, the JLS requires ("in accordance with the rules of the IEEE 754 standard") that:

Positive zero and negative zero are considered equal.

hence 0.0 == -0.0 is true.

这篇关于Java签名零和拳击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆