Java三元运算符里面的三元运算符,如何求值? [英] Java Ternary Operator inside ternary operator, how evaluated?

查看:111
本文介绍了Java三元运算符里面的三元运算符,如何求值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Very basic question I suppose, I just wanted to know how this code is read:

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

我想我现在正在写这篇文章,我很理解这个说法。如果为true,则返回选项1,但是然后另一个布尔值检查是否为false,并返回其余两个选项之一?我将继续离开这个问题,因为我以前从未见过,也许其他人也没有。

I guess now as I'm writing it I kind of understand the statement. It returns option one if true but then does another boolean check if false and returns one of the two remaining options? I'm going to continue to leave this question because I have not seen it before and maybe others have not as well.

您能否无限期地进行三元运算内部的三元运算?

Could you go on indefinitely with ternary inside of ternary operations?

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

Also why is this/is this not better for code than using a bunch of if statements?

推荐答案

它在 JLS#15.25


条件运算符在语法上右关联(从右到左分组)。因此, 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());

这篇关于Java三元运算符里面的三元运算符,如何求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆