数学世界
在数学中,不存在模糊的概念,等号(=)定义了一种真实的数之间的等价关系,满足自反性,传递性,对称性。
自反性:对于所有 x,x = x。也就是说,每个值与其自身存在相等关系 。
传递性:如果 x = y 并且 y = z,那么 x = z。
对称性:如果 x = y,那么 y = x。
Java 世界
Java 中存在 == 用来表示相等的关系,那么它满足自反性,传递性和对称性吗?能否提供一段程序来演示它是否违反了任意性质?
1.自反性的例子
publicstaticvoidmain(String[] args) { inti=5; System.out.println("x is int x = x : "+(i==5)); floatf=Float.NaN; System.out.println("x is float nan x=x :"+(f==Float.NaN)); doubled=Double.NaN; System.out.println("x is double nan x=x :"+(d==Double.NaN)); }
输出结果:
xisintx=x : truexisfloatnanx=x :falsexisdoublenanx=x :false
从上面的实例来看,== 不具有自反性。
2.传递性
publicstaticvoidmain(String[] args) { longx=Long.MAX_VALUE; doubley= (double) Long.MAX_VALUE; longz=Long.MAX_VALUE-1; System.out.println((x==y) +""); // 不精确的!System.out.println((y==z) +""); // 不精确的!System.out.println(x==z); // 精确的! }
输出结果为:
truetruefalse
传递性有问题。
3.对称性
publicstaticvoidmain(String[] args) { inti=5,j=5; System.out.println("x y is int x = y : "+(i==j)); floatf=0.53f,f1=0.53f; System.out.println("x y is float x = y : "+(f==f1)); doubled=0.3836,d1=0.3836; System.out.println("x y is double x = y : "+(d==d1)); }
输出结果为:
x y is int x = y : truex y is float x = y : truex y is double x = y : true
总结
总之,Java 中的 == 使用时要警惕到 float 和 double 类型的拓宽原始类型转换所造成的损失。它们是悄无声息的,但却是致命的。它们会违反你的直觉,并且可以造成非常微妙的错误。
