我想要在一个哈希映射
中使用 Double
(或者 Float
)类型作为键。
Map<Double, String> map = new HashMap<Double, String>()
map.put(1.0, "one");
System.out.println(map.containsKey(Math.tan(Math.PI / 4)));
这将返回false。
如果我要比较这两个数字,我会这样做:
final double EPSILON = 1e-6;
Math.abs(1.0 - Math.tan(Math.PI / 4)) < EPSILON
但是由于Hashmap
使用了hashcode
,这对我造成了一些困扰。
我考虑实现一个roundKey
函数,在将其用作键之前,将其舍入为EPSILON
的某个倍数。
map.put(roundKey(1.0), "one")
map.containsKey(roundKey(Math.tan(Math.PI / 4)))
- 有没有更好的方法?
- 如何正确实现这个
roundKey
?