首页 文章

Java三元运算符内部的三元运算符,如何评估?

提问于
浏览
4

我想这是一个非常基本的问题,我只是想知道如何读取这段代码:

return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance();

我想我现在正在写它,我有点理解这句话 . 如果为true,则返回选项1,但如果为false则返回另一个布尔检查并返回剩下的两个选项之一?我将继续留下这个问题,因为我之前没有看到它,也许其他人也没有 .

你可以在三元运算中无限期地继续三元运动吗?

编辑:为什么这个/这不是更好的代码而不是使用一堆if语句?

2 回答

  • 5

    它在_2584562中定义:

    条件运算符在语法上是右关联的(它从右到左分组) . 因此,a?b:c?d:e?f:g表示与a b相同:(c?d:(e?f:g)) .

    在你的情况下,

    return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance();
    

    相当于:

    return someboolean ? new someinstanceofsomething() : (someotherboolean ? new otherinstance() : new third instance());
    
  • 15

    三元运算符是右关联的 . 有关JLS参考,请参阅assylias的答案 .

    您的示例将转换为:

    if (someboolean) {
      return new someinstanceofsomething();
    } else {
      if (someotherboolean) {
        return new otherinstance();
      } else {
        return new thirdinstance()
      }
    }
    

    是的,你可以无限期地嵌套它们 .

相关问题