简体   繁体   中英

“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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM