什么是Java?:运算符被调用,它做了什么? [英] What is the Java ?: operator called and what does it do?
问题描述
我一直在使用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 <$ c调用$ c> getAwayCount()。
- if
isHere
is true,getHereCount()
is called, - if
isHere
is falsegetAwayCount()
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条件运算符? :
条件运算符
? :
使用一个表达式的布尔值来决定应该评估两个其他表达式中的哪一个。
§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
这篇关于什么是Java?:运算符被调用,它做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!