在HashMap中加倍 [英] Double in HashMap

查看:130
本文介绍了在HashMap中加倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用Double作为HashMap的关键,但我知道浮点数比较是不安全的,这让我思考。 Double类上的equals方法也不安全吗?如果那样则意味着hashCode方法可能也是错误的。这意味着使用Double作为HashMap的关键将导致不可预测的行为。

I was thinking of using a Double as the key to a HashMap but I know floating point comparisons are unsafe, that got me thinking. Is the equals method on the Double class also unsafe? If it is then that would mean the hashCode method is probably also incorrect. This would mean that using Double as the key to a HashMap would lead to unpredictable behavior.

任何人都可以在此确认我的推测吗?

Can anyone confirm any of my speculation here?

推荐答案

简答:不要这样做

答案很长:以下是密钥的计算方法:

Long answer: Here is how the key is going to be computed:

实际的密钥是 java.lang.Double object,因为键必须是对象。这是 hashCode()方法:

The actual key will be a java.lang.Double object, since keys must be objects. Here is its hashCode() method:

public int hashCode() {
  long bits = doubleToLongBits(value);
  return (int)(bits ^ (bits >>> 32));
}

doubleToLongBits()方法基本上占用8个字节并将它们表示为long。因此,这意味着双倍计算中的微小变化意味着很多,而且你会遇到关键的失误。

The doubleToLongBits() method basically takes the 8 bytes and represent them as long. So it means that small changes in the computation of double can mean a great deal and you will have key misses.

如果你能在之后获得一定数量的积分dot - 乘以10 ^(点后的位数)并转换为int(例如 - 2位乘以100)。

If you can settle for a given number of points after the dot - multiply by 10^(number of digits after the dot) and convert to int (for example - for 2 digits multiply by 100).

它会更安全。

这篇关于在HashMap中加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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