平等と比較のための特別な値はいくつかあります。これらは、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は==0.0ですが、compareTo(-0.0、0.0)の場合は-1を返します