gpt4 book ai didi

Java 双重比较与字符串比较

转载 作者:行者123 更新时间:2023-11-30 08:55:31 24 4
gpt4 key购买 nike

我遇到了一些旧的遗留代码,如下所示:

s1 = Double.toString(dbVal1);
s2 = Double.toString(dbVal2);
if (s1.compareTo(s2)!=0)
{
return false;
}
return true;

其中 dbVal1dbVal2 都是 double 值。

我在分析时发现了这一点,toString 方法调用占用了相当多的 CPU 时间。有什么理由我不能用 1 或 2 替换它吗?如果是这样,有什么区别/哪个更好?

1.

return dbVal1 == dbVal2;

2.

return Double.compare(dbVal1,dbVal2) == 0;

最佳答案

Double 类提供了一个 compare 方法,将 NaN 视为相等。我已经测试了几个有趣的案例,在每个案例中它都给出了与更间接的 String 方法相同的结果:

public class Test {
public static void main(String[] args) {
testit(0.0,0.0);
testit(0.0, -0.0);
testit(Double.NaN, Double.NaN);
testit(Double.NaN, 3.0);
testit(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
testit(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
}

private static void testit(double a, double b) {
boolean doubleEquals = (a == b);
boolean doubleCompare = Double.compare(a, b) == 0;
boolean stringCompare = Double.toString(a).compareTo(Double.toString(b)) == 0;
if(doubleCompare != stringCompare){
System.out.print("* ");
}
System.out.println("a=" + a + " b=" + b + " double == " + doubleEquals
+ " Double compare " + doubleCompare + " String compare "
+ stringCompare);
}
}

输出:

a=0.0 b=0.0 double == true Double compare true String compare true
a=0.0 b=-0.0 double == true Double compare false String compare false
a=NaN b=NaN double == false Double compare true String compare true
a=NaN b=3.0 double == false Double compare false String compare false
a=Infinity b=Infinity double == true Double compare true String compare true
a=-Infinity b=-Infinity double == true Double compare true String compare true

关于Java 双重比较与字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972497/

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