有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

我想在我写这篇文章的时候,我已经理解了这句话。如果为true,则返回选项1,如果为false,则执行另一个布尔值检查,并返回剩余两个选项中的一个?我将继续留下这个问题,因为我以前没见过,也许其他人也没见过

你能在三元运算中无限期地进行三元运算吗

编辑:为什么这/这对代码来说不比使用一堆if语句更好


共 (2) 个答案

  1. # 1 楼答案

    它在JLS #15.25中定义:

    The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as 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());
    
  2. # 2 楼答案

    三元运算符是右结合的。有关JLS参考,请参见assylias的答案

    你的例子可以转化为:

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

    是的,你可以无限期地嵌套这些