Java: different double compared with double

I know that double is a wrapper class that contains even numbers Today I see another major difference:

double a = 1.0;
double b = 1.0;
Double c = 1.0;
Double d = 1.0;
System.out.println(a == b);  // true
System.out.println(c == d);  // false

I'm strange!

Therefore, if we use double, we must do this every time:

private static final double delta = 0.0001;
System.out.println(Math.abs(c-d) < delta);

I can't explain why double is directly wrong Please explain for me

Thank you:)

Solution

C and D are technically two different objects, and the = = operator only compares references

c.equals(d)

It is better to compare value than reference But still not ideal Direct comparison of floating-point values should always consider some errors( ε) (Math.abs(c-d)< epsilon). be careful:

Integer c = 1;
Integer d = 1;

The comparison here will produce real, but this is more complex (integer internal cache, described in Javadoc of integer. Valueof()):

Why valueof()? Because this method is implicitly used to realize automatic boxing:

Integer c = Integer.valueOf(1);
Integer d = Integer.valueOf(1);

You can also have a look

> Weird Integer boxing in Java > How to properly compare two Integers in Java?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>