我遇到过一些情况,其中第一个似乎改变了 boolean 值,而第二个却没有!两者之间有真正的区别吗:
boolean x = true;
if (x != true) {}
if (!x) {}
最佳答案
不,没有。
尽管有些人认为第二个习语更优雅(不那么麻烦和冗长)。
有一个问题!
!=
运算符用于对象引用相等,因此在使用包装器 Boolean
而不是基元的边缘情况场景中...
Boolean b0 = new Boolean("true"); // value true
Boolean b1 = new Boolean("true"); // value true as well
System.out.println(!b0); // prints false
System.out.println(!b1); // prints false too
System.out.println(b0 != b1); // references not equal, prints true!
输出
true
关于java - if (!statement) 和 if (statement != true) 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34726929/