只有几个特殊值用于相等和比较。它们是 Float.NaN、Double.NaN、-0.0f 和 -0.0。
这些特殊的原因是它们不遵循一些正常的相等或 compareTo 规则
public static void main(String... args) {
printComparisons("Float.NaN", Float.NaN);
printComparisons("Double.NaN", Double.NaN);
printComparisons("-0.0f", -0.0f);
printComparisons("-0.0", -0.0);
}
private static void printComparisons(String desc, float v) {
System.out.println("[ " + desc + " ]");
System.out.println(v + " == " + v + " is " + (v == v));
System.out.println(v + " != " + v + " is " + (v != v));
System.out.println(v + " == 0.0 is " + (v == 0.0));
System.out.println(v + " < 0 is " + (v < 0));
System.out.println(v + " > 0 is " + (v > 0));
System.out.println("Float.compareTo(" + v + ", 0) is " + Float.compare(v, 0));
System.out.println();
}
private static void printComparisons(String desc, double v) {
System.out.println("[ " + desc + " ]");
System.out.println(v + " == " + v + " is " + (v == v));
System.out.println(v + " != " + v + " is " + (v != v));
System.out.println(v + " == 0.0 is " + (v == 0.0));
System.out.println(v + " < 0 is " + (v < 0));
System.out.println(v + " > 0 is " + (v > 0));
System.out.println("Double.compareTo(" + v + ", 0) is " + Double.compare(v, 0));
System.out.println();
}
印刷
[ Float.NaN ]
NaN == NaN is false
NaN != NaN is true
NaN == 0.0 is false
NaN < 0 is false
NaN > 0 is false
Float.compareTo(NaN, 0) is 1
[ Double.NaN ]
NaN == NaN is false
NaN != NaN is true
NaN == 0.0 is false
NaN < 0 is false
NaN > 0 is false
Double.compareTo(NaN, 0) is 1
[ -0.0f ]
-0.0 == -0.0 is true
-0.0 != -0.0 is false
-0.0 == 0.0 is true
-0.0 < 0 is false
-0.0 > 0 is false
Float.compareTo(-0.0, 0) is -1
[ -0.0 ]
-0.0 == -0.0 is true
-0.0 != -0.0 is false
-0.0 == 0.0 is true
-0.0 < 0 is false
-0.0 > 0 is false
Double.compareTo(-0.0, 0) is -1
总之。
- NaN 不是 >、<、==、>= 或 <= 0.0,而是
compareTo(NaN,0)
返回 1
- 0.0 is == 0.0 but for compareTo(-0.0, 0.0) return -1