Reputation: 4898
Please see the code below.
"Double"(upper D) is used in HashSet, and "double" is used for x1, x2 and x3. After x1 is added to the HashSet, x2 cannot be added, but x3 can! 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 = 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
Upvotes: 2
Views: 1522
Reputation: 1280
HashSet<E>
only allows unique values, unlike List<E>
.
x1 = (double)0/1;
equals to 0.0
, same as x2 = 0.0 + (double)0/2;
. While x3 = (double)0/-1;
equals to -0.0
. This is why you can add the first and third element but not the second.
When to use HashSet then? What is the pro of it over List
?
That has already been answered here HashSet vs. List performance, which I recommend you to read.
Some minor things of your code.
I see no reason to mix Double and double, stick to one for easier reading. Java : different double and Double in comparison
Normally one would write it as Set<Double> hs = new HashSet<>();
Note that it is only supported to use the Diamond Operator in Java 7+. You can read more of it here What is the point of the diamond operator in Java 7?.
Upvotes: 0
Reputation: 37033
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.
Upvotes: 3