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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/798545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:37:11  来源:igfitidea点击:

What is the Java ?: operator called and what does it do?

javasyntaxternary-operatorconditional-operator

提问by mainstringargs

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

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

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.

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

  • if isHereis true, getHereCount()is called,
  • if isHereis false getAwayCount()is called.
  • 如果isHere是真的,getHereCount()被称为,
  • 如果isHere是假getAwayCount()被调用。

Correct? What is this construct called?

正确的?这个构造叫什么?

采纳答案by Michael Myers

Yes, it is a shorthand form of

是的,它是一种简写形式

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

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 couldbe another ternary operator, whereas there can only be one conditional operator.

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

The official name is given in the Java Language Specification:

官方名称在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.

§15.25 条件运算符?:

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

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

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

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.

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

事实上,根据表达式语句的语法(第14.8 节),条件表达式不允许出现在任何可能出现 void 方法调用的上下文中。

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

因此,如果doSomething()doSomethingElse()是 void 方法,则无法压缩:

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

into this:

进入这个:

someBool ? doSomething() : doSomethingElse();

Simple words:

简单的话:

booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse 

回答by cletus

Correct. It's calledthe ternary operator. Some also call it the conditional operator.

正确的。它三元运算符。有些人也称它为条件运算符

回答by Romain Linsolas

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

means :

方法 :

if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

回答by Gary

Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.

是的,你是对的。?: 通常称为“三元条件运算符”,通常简称为“三元运算符”。它是标准 if/else 条件的简写版本。

Ternary Conditional Operator

三元条件运算符

回答by Joe Phillips

condition ? truth : false;

If the condition is truethen return the first parameter. If the condition is false, return the second parameter.

如果条件是,true则返回第一个参数。如果条件为false,则返回第二个参数。

It is called the Conditional Operatorand it is a type of Ternary Operation.

它被称为条件运算符,它是一种三元运算

回答by JRL

According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.

根据Sun Java 规范,它被称为条件运算符。见第 15.25 节。你是对的。

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

条件运算符 ? : 使用一个表达式的布尔值来决定应该评估另外两个表达式中的哪一个。

The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

条件运算符在语法上是右结合的(它从右到左分组),因此 a?b:c?d:e?f:g 与 a?b:(c?d:(e?f :G))。

ConditionalExpression:
        ConditionalOrExpression
        ConditionalOrExpression ? Expression : ConditionalExpression

The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

条件运算符具有三个操作数表达式;? 出现在第一个和第二个表达式之间,并且 : 出现在第二个和第三个表达式之间。

The first expression must be of type boolean or Boolean, or a compile-time error occurs.

第一个表达式必须是 boolean 或 Boolean 类型,否则会发生编译时错误。

回答by justinhj

It's the conditional operator, and it's more than just a concise way of writing if statements.

它是条件运算符,它不仅仅是编写 if 语句的简洁方式。

Since it is an expression that returns a value it can be used as part of other expressions.

由于它是一个返回值的表达式,因此它可以用作其他表达式的一部分。

回答by Jon Skeet

Others have answered this to reasonable extent, but often with the name "ternary operator".

其他人已经在合理范围内回答了这个问题,但通常使用“三元运算符”这个名称。

Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's aternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.

作为学究的我,我想明确说明运算符的名称是条件运算符或“条件运算符 ?:”。它是一个三元运算符(因为它有三个操作数)并且它恰好是目前 Java 中唯一的三元运算符。

However, the spec is pretty clearthat its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.

但是,规范非常清楚,它的名称是条件运算符或“条件运算符 ?:”,绝对不含糊。我认为用这个名字来称呼它更清楚,因为它在某种程度上表明了运算符的行为(评估条件),而不仅仅是它有多少个操作数。

回答by RichN

Not exactly correct, to be precise:

不完全正确,准确地说:

  1. if isHere is true, the resultof getHereCount() is returned
  2. otheriwse the resultof getAwayCount() is returned
  1. 如果 isHere 为真,则返回getHereCount()的结果
  2. 否则返回getAwayCount()的结果

That "returned" is very important. It means the methods mustreturn a value and that value mustbe assigned somewhere.

那个“返回”很重要。这意味着方法必须返回一个值,并且该值必须被分配到某个地方。

Also, it's not exactlysyntactically equivalent to the if-else version. For example:

此外,它在语法上并不完全等同于 if-else 版本。例如:

String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;

If coded with if-else will always result in more bytecode.

如果用 if-else 编码将总是产生更多的字节码。

回答by Bill K

I happen to really like this operator, but the reader should be taken into consideration.

我碰巧很喜欢这个运算符,但应该考虑到读者。

You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.

你总是必须在代码紧凑性和阅读时间之间取得平衡,因为它有一些非常严重的缺陷。

First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.

首先,有原始提问者的情况。他只花了一个小时发布它并阅读回复。作者在他的一生中将每一个 ?: 写成 if/then 需要多长时间。不是一个小时可以肯定。

Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:

其次,在类 C 语言中,您习惯于简单地知道条件是行中的第一件事。我在使用 Ruby 时注意到了这一点,并遇到了如下几行:

callMethodWhatever(Long + Expression + with + syntax) if conditional

If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.

如果我是 Ruby 的长期用户,我可能不会对这一行有任何问题,但是来自 C,当您看到“callMethodWhatever”作为该行中的第一件事时,您希望它被执行。?: 不太神秘,但仍然不寻常,足以让读者望而却步。

The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.

但是,当您可以在其中 1 行的空间中编写 3 行 if 语句时,其优点是在您的肚子里感觉非常酷。不能否认:) 但老实说,仅仅因为它的稀有性,90% 的人不一定更容易阅读。

When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.

当它真正是基于布尔值和值的赋值时,我没有问题,但它很容易被滥用。