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

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

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

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

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

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

它在JLS#15.25中定义:

条件运算符在语法上是右关联的(它从右到左分组)。 因此, a?b:c?d:e?f:g表示与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()); 

三元运算符是右关联的。 请参阅assylias对JLS参考的回答。

您的示例将转换为:

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

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