[英]“double, Double, HashSet” in Java
Please see the code below. 请参见下面的代码。
"Double"(upper D) is used in HashSet, and "double" is used for x1, x2 and x3. HashSet中使用“ Double”(上D),而x1,x2和x3使用“ double”。 After x1 is added to the HashSet, x2 cannot be added, but x3 can!
在将x1添加到HashSet之后,无法添加x2,但是可以添加x3! Why??????
为什么??????
Thanks in advance :) 提前致谢 :)
HashSet<Double> hs = new HashSet<Double>();
double x1, x2, x3;
x1 = (double)0/1;
System.out.println(hs.add(x1)); //true
x2 = (double)0/2;
System.out.println(hs.add(x2)); //false
x3 = (double)0/-1;
System.out.println(hs.add(x3)); //true
And if you add "0.0 +" for x1, x2 and x3, the result is as follows. 并且,如果为x1,x2和x3添加“ 0.0 +”,则结果如下。
x1 = 0.0 + (double)0/1;
System.out.println(hs.add(x1)); //true
x2 = 0.0 + (double)0/2;
System.out.println(hs.add(x2)); //false
x3 = 0.0 + (double)0/-1;
System.out.println(hs.add(x3)); //false
Try this to understand difference: 尝试一下以了解差异:
HashSet<Double> hs = new HashSet<Double>();
double x1, x2, x3;
x1 = (double)0/1;
System.out.println(x1 + " "+ hs.add(x1)); //true
x2 = (double)0/2;
System.out.println(x2 + " " + hs.add(x2)); //false
x3 = (double)0/-1;
System.out.println(x3 + " " + hs.add(x3)); //true
Basically doubles are signed and 0/-1 will be evaluated as -0.0 instead of 0.0 by x1 or x2. 基本上双精度符号是有符号的,并且x1或x2将0 / -1的值计算为-0.0而不是0.0。
HashSet<E>
only allows unique values, unlike List<E>
. 与
List<E>
不同, HashSet<E>
仅允许唯一值。
x1 = (double)0/1;
equals to 0.0
, same as x2 = 0.0 + (double)0/2;
等于
0.0
,与x2 = 0.0 + (double)0/2;
. 。 While
x3 = (double)0/-1;
而
x3 = (double)0/-1;
equals to -0.0
. 等于
-0.0
。 This is why you can add the first and third element but not the second. 这就是为什么您可以添加第一个和第三个元素而不添加第二个元素的原因。
When to use HashSet then? 什么时候使用HashSet? What is the pro of it over
List
? List
的优点是什么?
That has already been answered here HashSet vs. List performance , which I recommend you to read. 我已经在这里建议您阅读HashSet vs. List performance了 。
Some minor things of your code. 您的代码中的一些小事情。
I see no reason to mix Double and double, stick to one for easier reading. 我认为没有理由将Double和Double混为一谈,坚持阅读以便于阅读。 Java : different double and Double in comparison
Java:不同的double和Double的比较
Normally one would write it as Set<Double> hs = new HashSet<>();
通常将其写为
Set<Double> hs = new HashSet<>();
Note that it is only supported to use the Diamond Operator in Java 7+. 请注意,仅在Java 7+中支持使用Diamond运算符。 You can read more of it here What is the point of the diamond operator in Java 7?
您可以在此处阅读更多内容。Java 7中diamond运算符的作用是什么? .
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.