【问题标题】:difference between if ( !statement) and if (statement != true)? [duplicate]if(!statement)和if(statement!= true)之间的区别? [复制]
【发布时间】:2016-04-16 01:55:46
【问题描述】:

我遇到过一些情况,其中 first 似乎改变了 Boolean 的值,而 second 没有!两者之间是否有真正的区别:

boolean x = true;

if (x != true) {}
if (!x) {}

【问题讨论】:

  • 没区别,但第二个更优雅
  • 除了所有答案之外,Java 编译器还会在遇到字节码时对其进行优化。两者都是单一的 IFNE。
  • 对我来说,不同之处在于 if (x != true) 看起来像是由没有正确理解布尔值的人编写的。

标签: java android


【解决方案1】:

这两个句子之间没有区别。 x != true 等于 !x

如果您将布尔变量与 equal 比较器进行比较,则可能会引入错误。例子:

if (x == false) {} // executes the "if" body when "x" is false

if (!x) {} // same of previous example, executes the "if" body when "x" is false

if (x = false) {} // assign the "false" value to x, and never executes the "if" body

最后一个示例使用单个“=”字符,并分配一个值。第一个示例使用两个“=”字符,并比较两个值而不分配任何内容。

【讨论】:

    【解决方案2】:

    在java中!=代表不相等,!代表不相等:

     x != ture // X not equal true (x = false)
    
     !x // Not x (x = true, not x = false)
    

    所以他们是平等的。

    【讨论】:

      【解决方案3】:

      不,没有。

      尽管有些人认为第二个成语更优雅(不那么繁琐和冗长)。

      有一个问题!

      != 运算符用于对象引用相等性,因此在边缘情况下使用包装器 Booleans 而不是原语...

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 2012-09-21
        • 2018-12-27
        • 1970-01-01
        • 2011-03-17
        相关资源
        最近更新 更多