对于原始值,Java的==
运算符可以非对称,以便x == y
,但是y != x
,其中{{1} }和x
都是某些(可能不同的)基元类型的变量?
修改
好的,我会说实话的原因。在Java Puzzlers book中,有一个谜题#87涉及基本类型的y
运算符。
它有三个部分,一个是挑战读者,以找到==
运算符不反映的情况,第二个是查找==
不可传递的情况。我找到了两者的解决方案,但我不知道如何解决第三个问题,其定义如下:
==
我没有这本书,所以我无法查找解决方案,我只查看了源文件,其中不包含解决方案。
答案 0 :(得分:4)
没有。对于所有基元,==符号为commutative。也就是说,
(x == y)=> (y == x)
答案 1 :(得分:4)
==
每个类型对称
来自规范:
如果操作数表达式没有边,则相等运算符是可交换的 的效果。
答案 2 :(得分:4)
对于相等和比较,只有一些特殊值。这些是Float.NaN,Double.NaN,-0.0f和-0.0。
这些特殊的原因是他们没有遵循一些正常的平等规则或者比较
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
总结。
compareTo(NaN,0)
返回1 答案 3 :(得分:2)
我不知道任何基本类型都适用的情况。