2

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
6324
  • 4,678
  • 8
  • 34
  • 63

2 Answers2

3

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.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • Thank you so much, I understand the difference now! – 6324 Dec 06 '14 at 07:29
  • @YilongWang, if the answer is sufficient to you then you should accept the answer. When other users have the same question as you they will easier see a correct answer. – Emz Dec 06 '14 at 07:34
  • @Maksym you need to refer this post http://stackoverflow.com/questions/14771328/java-signed-zero-and-boxing – SMA Dec 06 '14 at 07:36
0

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.

Community
  • 1
  • 1
Emz
  • 1,280
  • 1
  • 14
  • 29