具有逻辑运算符的Java简写三元运算符

时间:2013-04-09 22:10:49

标签: java performance

我对java很新,所以请耐心等待。我正在尝试压缩我的一些代码,并想知道你是如何使用&&编写一个三元运算符的。或者是||。那么我如何将下面的代码转换成速记三元运算符。

if(homePage != null && currentParentPage.getPath().equals(homePage.getPath())){
    isParent = true;
}

3 个答案:

答案 0 :(得分:2)

实际上,要将代码转换为三元组,您必须编码

isParent = (homePage != null && currentParentPage.getPath().equals(homePage.getPath()))
           ? true : isParent;

isParent = (homePage != null && currentParentPage.getPath().equals(homePage.getPath()));

isParent = (homePage != null && currentParentPage.getPath().equals(homePage.getPath()))
            ? true : false;

在false leg上修改isParent,这不是原始代码所做的。

答案 1 :(得分:1)

三元运算符旨在表示if-else情况。您的案例只包含if子句,因此您不需要。如果明确要将isParent设置为false,则可以使用一个,如果失败,即

isParent = (homePage != null &&
  currentParentPage.getPath().equals(homePage.getPath()))  ? true  :  false;

这意味着如果之前的条件?保持为true,返回第一个值(true),否则返回第二个值(false)。

根据下面的评论,你真的不需要使用三元组进行布尔赋值。这可以简化为:

    isParent = (homePage != null &&
  currentParentPage.getPath().equals(homePage.getPath()));

答案 2 :(得分:1)

(homePage != null && currentParentPage.getPath().equals(homePage.getPath()))
        ? isParent = true
        : isParent = false;

我建议以最简单的方式执行此操作 - 而不是使用三元操作

 isParent = (homePage != null && currentParentPage.getPath().equals(homePage.getPath()));
相关问题