什么是 Java ?: 运算符,它的作用是什么?

我已经使用 Java 几年了,但直到最近我还没有遇到过这种结构:

I have been working with Java a couple of years, but up until recently I haven't run across this construct:

int count = isHere ? getHereCount(index) : getAwayCount(index);

这可能是一个非常简单的问题,但有人可以解释一下吗?我该如何阅读?我很确定我知道它是如何工作的.

This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.

  • 如果 isHere 为真,则调用 getHereCount()
  • 如果 isHere 为 false,则调用 getAwayCount().
  • if isHere is true, getHereCount() is called,
  • if isHere is false getAwayCount() is called.

对吗?这个结构叫什么?

Correct? What is this construct called?

推荐答案

是的,是简写形式

int count;
if (isHere)
    count = getHereCount(index);
else
    count = getAwayCount(index);

称为条件运算符.许多人(错误地)称它为 三元运算符,因为它是 Java、C、C++ 以及可能许多其他语言中唯一的三元(三参数)运算符.但是理论上可能还有一个三元运算符,而条件运算符只能有一个.

It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.

官方名称在 Java 语言规范:

条件运算符 ?: 使用一个表达式的布尔值来决定应该计算其他两个表达式中的哪一个.

§15.25 Conditional Operator ? :

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

注意,两个分支都必须指向有返回值的方法:

Note that both branches must lead to methods with return values:

第二个或第三个操作数表达式调用 void 方法是编译时错误.

其实通过表达式语句的语法(§14.8),条件表达式不允许出现在任何可能出现 void 方法调用的上下文中.

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 方法,则不能压缩:

So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:

if (someBool)
    doSomething();
else
    doSomethingElse();

进入这个:

someBool ? doSomething() : doSomethingElse();

简单的话:

booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse 

相关文章