Ealon
Ealon

Reputation: 4898

"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. 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

Answers (2)

Emz
Emz

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.

Upvotes: 0

SMA
SMA

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

Related Questions