Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

java - Difference between double and Double in comparison

I know that Double is a a wrapper class, and it wraps double number. Today, I have seen another main 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

So strange with me !!!

So, if we use Double, each time, we must do something like this :

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

I cannot explain why Double make directly comparison wrong. Please explain for me.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

c and d are technically two different objects and == operator compares only references.

c.equals(d)

is better as it compares values, not references. But still not ideal. Comparing floating-point values directly should always take some error (epsilon) into account (Math.abs(c - d) < epsilon).

Note that:

Integer c = 1;
Integer d = 1;

here comparison would yield true, but that's more complicated (Integer internal caching, described in JavaDoc of Integer.valueOf()):

This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

Why valueOf()? Because this method is implicitly used to implement autoboxing:

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

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...