Java ?: 运算符的名称是什么?它有什么作用?
我使用 Java 已经有几年了,但直到最近我还没有遇到过这个构造:
int count = isHere ? getHereCount(index) : getAwayCount(index);
这可能是一个非常简单的问题,但是有人可以解释一下吗? 我该如何阅读它? 我很确定我知道它是如何工作的。
- 如果
isHere
为 true,则调用getHereCount()
, - 如果
isHere
为 false,则调用getAwayCount()
。
正确的? 这个构造叫什么?
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.
- if
isHere
is true,getHereCount()
is called, - if
isHere
is falsegetAwayCount()
is called.
Correct? What is this construct called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
的简写形式
是的,它是“条件运算符” 。 许多人(错误地)将其称为三元运算符,因为它是 Java、C、C++ 以及可能许多其他语言中唯一的三元(三参数)运算符。 但理论上,可能还有另一个三元运算符,而只能有一个条件运算符。
正式名称在 Java 语言中给出规格:
请注意,两个分支都必须指向具有返回值的方法:
因此,如果
doSomething()
和doSomethingElse() 是 void 方法,你不能将 this: 压缩
成 this:
简单的话:
Yes, it is a shorthand form of
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.
The official name is given in the Java Language Specification:
Note that both branches must lead to methods with return values:
So, if
doSomething()
anddoSomethingElse()
are void methods, you cannot compress this:into this:
Simple words:
其他人已经在合理的范围内回答了这个问题,但通常使用“三元运算符”的名称。
作为学究,我想澄清一下,运算符的名称是条件运算符或“条件运算符?:”。 它是一个三元运算符(因为它有三个操作数),而且它恰好是目前 Java 中唯一的三元运算符。
但是,规范非常明确 其名称是条件运算符或“条件运算符?:”,绝对不含糊。 我认为用这个名字来称呼它更清楚,因为它在某种程度上指示了运算符的行为(评估条件),而不仅仅是它有多少个操作数。
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 a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that 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.
根据 Sun Java 规范,它被称为条件运算符。 参见第 15.25 节。 你对它的作用是对的。
条件运算符 ? :使用一个表达式的布尔值来决定应计算另外两个表达式中的哪一个。
条件运算符在语法上是右关联的(它从右到左分组),因此 a?b:c?d:e?f:g 与 a?b:(c?d:(e?f :G))。
条件运算符有三个操作数表达式; ? 出现在第一个和第二个表达式之间,并且 : 出现在第二个和第三个表达式之间。
第一个表达式必须是 boolean 或 Boolean 类型,否则会发生编译时错误。
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
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)).
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.
如果条件为
true
,则计算第一个表达式。 如果条件为false
,则计算第二个表达式。它称为 条件运算符,它是 三元运算。
If the condition is
true
then evaluate the first expression. If the condition isfalse
, evaluate the second expression.It is called the Conditional Operator and it is a type of Ternary Operation.
方法 :
means :
准确地说,并不完全正确:
这个“返回”非常重要。 这意味着方法必须返回一个值,并且该值必须分配到某个地方。
此外,它在语法上不完全等同于 if-else 版本。 例如:
如果用 if-else 编码总是会产生更多的字节码。
Not exactly correct, to be precise:
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
If coded with if-else will always result in more bytecode.
三元,有条件; 番茄,番茄。 它真正有价值的是变量初始化。 如果(像我一样)您喜欢在定义变量的地方初始化变量,则条件三元运算符(因为它是两者)允许您在其值有条件的情况下执行此操作。 在 Final 领域尤其值得注意,但在其他领域也很有用。
例如:
如果没有该运算符 - 无论名称如何 - 您都必须使该字段成为非最终字段或编写一个函数来简单地初始化它。实际上,这是不对的 - 它仍然可以使用 if/ 进行初始化否则,至少在 Java 中是这样。 但我发现这更干净。
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
您可能对提案感兴趣一些类似于条件运算符的新运算符。 空安全运算符将启用如下代码:
在进行自动拆箱的情况下会特别方便。
它已被 选择在 JDK 7 的“Project Coin”下进行进一步考虑。
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
It would be especially convenient where auto-unboxing takes place.
It has been selected for further consideration under JDK 7's "Project Coin."
这种构造在计算机科学和编程技术中称为三元运算符。
并且维基百科建议如下解释:
不仅在 Java 中,这种语法在 PHP、Objective-C 中也可用。
在下面的链接中给出了以下解释,这很容易理解它:
对于某些不太复杂的逻辑条件来说,这可能是可读的,否则最好使用 If-Else 块 与条件逻辑的预期组合。
我们可以使用此三元运算符来简化 If-Else 块,用于一个代码语句行。
例如:
可能等于以下内容:
因此,如果我们引用你的陈述:
它实际上 100% 等价于以下 If-Else 块:
就是这样!
希望这对某人有帮助!
干杯!
This construct is called Ternary Operator in Computer Science and Programing techniques.
And Wikipedia suggest the following explanation:
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.
For Example:
Might be equal to the following:
So if we refer to your statement:
It is actually the 100% equivalent of the following If-Else block:
That's it!
Hope this was helpful to somebody!
Cheers!
正确的。 它称为三元运算符。 有些人还称其为条件运算符。
Correct. It's called the ternary operator. Some also call it the conditional operator.
它的三元运算符(?:)
Its Ternary Operator(?:)
实际上,它可能需要 3 个以上的参数。
例如,如果我们想检查一个数字是正数、负数还是零,我们可以这样做:
这比使用 if、else if、else 更好。
Actually, it can take more than 3 arguments.
For instance, if we want to check whether a number is positive, negative, or zero, we can do this:
which is better than using if, else if, else.
?: 是一个三元 Java 运算符。
它的语法是:
这里,
条件
被评估并且条件
返回true
,表达式1
将执行.条件
返回false
,表达式2
将执行。公共类索尼代码{
公共静态无效主(字符串[] args){
双分 = 90;
字符串结果 = (分数 > 40) ? "考试通过" : "考试失败";
System.out.println("你的结果是:" + result);
}
}
输出 :-
?: is a Ternary Java Operator.
Its syntax is:
Here, the
condition
is evaluated andcondition
returnstrue
, theexpression1
will execute.condition
returnsfalse
, theexpression2
will execute.public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
它是条件运算符,它不仅仅是一种编写 if 语句的简洁方式。
由于它是一个返回值的表达式,因此可以用作其他表达式的一部分。
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
是的,你是对的。 ?: 通常称为“三元条件运算符”,通常简称为“三元运算符”。 它是标准 if/else 条件的简写版本。
三元条件运算符
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.
Ternary Conditional Operator
我恰好很喜欢这个操作符,但应该考虑到读者。
你总是必须平衡代码的紧凑性和阅读它所花费的时间,并且它有一些相当严重的缺陷。
首先,有原始提问者的案例。 他只花了一个小时发布相关内容并阅读回复。 作者在他的一生中将每一个“?:”都写成“如果/那么”需要多长时间。 可以肯定的是,不到一个小时。
其次,在类 C 语言中,您习惯于简单地知道条件语句是行中的第一个内容。 当我使用 Ruby 时,我注意到了这一点,并遇到了这样的行:
如果我是一个长期的 Ruby 用户,我可能不会对这行有问题,但是来自 C,当你看到“callMethodWhatever”作为第一件事时在该行中,您期望它被执行。 ?: 不那么神秘,但仍然不寻常,足以让读者感到困惑。
然而,这样做的好处是,当您可以在其中 1 行的空间中编写 3 行 if 语句时,您会感到非常凉爽。 不能否认这一点:) 但老实说,仅仅因为它的稀有性,90% 的人不一定更容易阅读。
当它确实是基于布尔值和值的分配时,我对此没有问题,但它很容易被滥用。
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.
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:
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.
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.
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.
条件表达式采用完全不同的风格,语句中没有明确的 if 。
语法是:
布尔表达式 ? 表达式1:表达式2;
该条件表达式的结果为
如果布尔表达式为真,则
表达式1; 否则结果是表达式2。
假设您要将变量 num1 和 num2 中较大的数字分配给 max。 您可以简单地使用条件表达式编写语句:
最大值 = (num1 > num2) ? 数字1:数字2;
注:符号? 和 : 一起出现在条件表达式中。 它们形成条件运算符,也称为三元运算符,因为它使用三个操作数。 它是Java中唯一的三元运算符。
引用自:《Java 编程入门》第 10 版,作者:Y. Daniel Liang,第 126 - 127 页
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127
是的,您解释得正确!
构造——三元条件运算符(也称为三元运算符或条件运算符)。
这是在一行中表达 if-else 语句的简写方式。
isHere - 布尔条件。
如果为真,则计算(问号)后面的表达式; 否则,将计算 :(冒号)后面的表达式。
如果 isHere 为 true,则调用 getHereCount(index) 并将其结果分配给变量 count。
如果 isHere 为 false,则调用 getAwayCount(index),并将其结果赋给变量 count。
Yes, you've interpreted it correctly!
The construct - ternary conditional operator (also known as the ternary operator or conditional operator).
It's a shorthand way of expressing an if-else statement in a single line.
isHere - boolean condition.
If it is true, the expression after the (question mark) is evaluated; otherwise, the expression after the : (colon) is evaluated.
If isHere is true, getHereCount(index) is called and its result is assigned to the variable count.
If isHere is false, getAwayCount(index) is called, and its result is assigned to the variable count.