Java:不同的double和double相比 [英] Java : different double and Double in comparison

查看:103
本文介绍了Java:不同的double和double相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 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);



另请参阅



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆