Java 中的双重比较失败

Double comparison failing in Java

为什么第一个 if-statement return 为真而第二个为假?

第一个if-statement中的100000000000000.032不也变成了一个新的不同于dd的Double吗?

Double dd = 100000000000000.032;
if(dd == 100000000000000.032) {
    System.out.println("gaga");
}

Double ee = 100000000000000.032;
if(dd == ee) {
    System.out.println("gaga");
}

由于您在第二个 if-statement 中比较两个对象,您应该使用 equals 方法,如下所示:

if(dd.equals(ee))

Double 是对象,所以 == 不会给出所需的结果,请使用 .equals 方法

== 测试对象是否是同一个对象,而不是它们具有相同的值。在您的示例中,ddee 是不同的对象,即使它们具有相同的值。所以如果你想比较它们的值,你需要使用 equals method.

这里有一个小测试可以帮助您掌握它:

package Whosebug;

import org.junit.jupiter.api.Test;

public class QuickTest {

    @Test
    public void test() throws Exception {
        Double number1 = 100000000000000.032;
        Double number2 = 100000000000000.032;

        System.out.println("Do they point to the same object? " + (number1 == number2));

        System.out.println("Are they equal, do they have the same value? " + (number1.equals(number2)));

        Double number3 = 100000000000000.032;
        Double number4 = number3;

        System.out.println("Do they point to the same object? " + (number3 == number4));

        System.out.println("Are they equal, do they have the same value? " + (number3.equals(number4)));
    }
}

这将打印出以下内容:

Do they point to the same object? false
Are they equal, do they have the same value? true
Do they point to the same object? true
Are they equal, do they have the same value? true

要么你跟随 Majed Badawi's 使用 equals() 因为你比较对象实例,或者你修改你的代码如下:

double dd = 100000000000000.032
if( dd == 100000000000000.032 ) 
{
    System.out.println( "gaga" );
}

double ee = 100000000000000.032;
if( dd == ee ) 
{
    System.out.println( "gaga" );
}

请注意 ddee 现在是基本类型 double(小写 'D')。

在您的示例中,第一次比较有效,因为在内部,它被解释为:

… 
if( dd.doubleValue() == 100000000000000.032 ) 
…

此行为称为 'Autoboxing/-unboxing' 并随 Java 5 引入;对于 Java 5 之前的版本,您的代码根本无法编译。

在第一个if中: - 你使用 == 来测试一个带有原语的对象;对象转换为原始类型,两者相等。 在第二个如果: - 你比较两个不同的对象。

试试 ee == ee 看看它 returns 正确。