我已经使用 Java 几年了,但直到最近我还没有遇到过这种结构:
int count = isHere ? getHereCount(index) : getAwayCount(index);
这可能是一个非常简单的问题,但有人可以解释一下吗?我该如何阅读?我很确定我知道它是如何工作的。
- 如果
isHere
为真,则调用getHereCount()
, - 如果
isHere
为 false,则调用getAwayCount()
。
对吗?这个结构叫什么?
最佳答案
是的,它是一种简写形式
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
称为条件运算符。许多人(错误地)称它为 三元运算符,因为它是 Java、C、C++ 以及可能许多其他语言中唯一的三元(三参数)运算符。但是理论上可能还有一个三元运算符,而条件运算符只能有一个。
官方名称在 Java Language Specification 中给出:
§15.25 Conditional Operator ? :
The conditional operator
? :
uses the boolean value of one expression to decide which of two other expressions should be evaluated.
注意,两个分支都必须指向有返回值的方法:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
所以,如果 doSomething()
和 doSomethingElse()
是 void 方法,则不能压缩:
if (someBool)
doSomething();
else
doSomethingElse();
进入这个:
someBool ? doSomething() : doSomethingElse();
简单的话:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
关于java - 什么是 Java ? : operator called and what does it do?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/798545/