gpt4 book ai didi

java - double 和 Double 比较的区别

转载 作者:太空狗 更新时间:2023-10-29 22:50:02 25 4
gpt4 key购买 nike

我知道 Double 是一个包装类,它包装了 double 数字。今天,我看到了另一个主要区别:

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,每次,我们都必须做这样的事情:

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

我无法解释为什么 Double 直接比较会出错。请为我解释一下。

最佳答案

cd技术上是两个不同的对象和==运算符只比较引用。

c.equals(d)

更好,因为它比较值,而不是引用。但仍然不理想。直接比较浮点值应该总是考虑一些错误(epsilon)(Math.abs(c - d) < epsilon)。

注意:

Integer c = 1;
Integer d = 1;

此处比较会产生 true ,但这更复杂( Integer 内部缓存,在 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.

为什么 valueOf() ?因为这个方法是隐式的用来实现自动装箱的:

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

另见

关于java - double 和 Double 比较的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12226757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com