Double与Double之间的差异比较 [英] Difference between double and Double in comparison

查看:211
本文介绍了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

我真奇怪!!!

因此,如果我们每次使用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.

推荐答案

cd从技术上讲是两个不同的对象,并且==运算符仅比较引用.

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);

另请参见

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