当我尝试这个时:
HashSet<Double> set = new HashSet<>();
Double d1 = new Double(0);
Double d2 = new Double(0);
Double d3 = new Double(-0);
set.add(d1);
System.out.println(set.contains(d2));
System.out.println(set.contains(d3));
输出是我所期望的:
true
true
但是当我尝试时:
HashSet<Double> set = new HashSet<>();
Double d1 = new Double(0.0);
Double d2 = new Double(0.0);
Double d3 = new Double(-0.0);
set.add(d1);
System.out.println(set.contains(d2));
System.out.println(set.contains(d3));
或
set.add(Double.valueOf(d1));
System.out.println(set.contains(Double.valueOf(d2)));
System.out.println(set.contains(Double.valueOf(d3)));
令我惊讶的是,输出是:
true
false
为什么会发生这种情况?如何使 HashSet 将 (0.0) 和 (-0.0) 视为相同?
还有比 if(num == -0.0) num = 0.0;
更好的方法吗? ?
最佳答案
这由 the docs 解释对于双
。
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.
因此,从 0.0
创建的 Double
与从 创建的
。当您使用 Double
不相同 - 0.00
和 -0
时,情况并非如此,因为整数使用补码,没有负零的概念。 -0
与 0
相同。另一方面,double
use the IEEE standard for floating point values ,它确实识别负零值。
此行为都是固定的,因此 HashSet
无法将 0.0
和 -0.0
视为相同。如果您想这样做,则需要在添加或搜索之前手动将所有负零值转换为正零值。
关于java - 为什么 HashSet 区分 0.0 和 -0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121455/