Java:不同的double和double相比 [英] Java : different 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
对我来说很奇怪!!!
So strange with me !!!
所以,如果我们每次使用 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
在技术上是两个不同的对象, ==
operator compare只有参考。
c
and d
are technically two different objects and ==
operator compares only references.
c.equals(d)
更好,因为它比较值,而不是引用。但仍然不理想。直接比较浮点值应该总是考虑一些错误(εilon)( 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
,但这是更复杂(整数
内部缓存,在 JavaDoc Integer.valueOf()
):
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
这篇关于Java:不同的double和double相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!