Double与Double之间的差异比较 [英] Difference between double and Double in comparison
问题描述
我知道Double
是包装类,并且包装double
数字.今天,我看到了另一个主要区别:
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
我真奇怪!!!
因此,如果我们每次使用Double
,则必须执行以下操作:
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);
我无法解释Double为何直接比较错误.请为我解释.
I cannot explain why Double make directly comparison wrong. Please explain for me.
推荐答案
c
和d
从技术上讲是两个不同的对象,并且==
运算符仅比较引用.
c
and d
are technically two different objects and ==
operator compares only references.
c.equals(d)
更好,因为它比较值而不是引用.但是仍然不理想.直接比较浮点值应始终将一些误差(ε)考虑在内(Math.abs(c - d) < epsilon
).
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
).
请注意:
Integer c = 1;
Integer d = 1;
在这里进行比较会产生true
,但这比较复杂(Integer
内部缓存,在
here comparison would yield true
, but that's more complicated (Integer
internal caching, described in JavaDoc of Integer.valueOf()
):
此方法将始终缓存-128至127(包括)范围内的值,并且可能会缓存该范围之外的其他值.
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
为什么valueOf()
?因为此方法隐式用于实现自动装箱:
Why valueOf()
? Because this method is implicitly used to implement autoboxing:
Integer c = Integer.valueOf(1);
Integer d = Integer.valueOf(1);
另请参见
- Java中的奇怪整数拳击
- 如何在Java中正确比较两个整数?
- Weird Integer boxing in Java
- How to properly compare two Integers in Java?
See also
这篇关于Double与Double之间的差异比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!