简体   繁体   English

三元对比如果在Java中

[英]Ternary vs if in Java

Why using ternary like this is incorrect where as using if is correct? 为什么使用这样的三元组是不正确的,因为使用if是正确的?

//Error when using as ternary
Character.isDigit(myDto.getNameStr().charAt(0)) ? digitArrayList.add(myDto) : charArrayList.add(myDto);

//OK when used as if ... else
char c = myDto.getNameStr().charAt(0);
if(Character.isDigit(c)) {
  digitArrayList.add(myDto);
} else {
  charArrayList.add(myDto);
}

The ternary conditional isn't allowed as a standalone statement. 三元条件不允许作为独立语句。 Only certain expressions are allowed as a standalone statement, like an assignment or a method call. 只允许某些表达式作为独立语句,如赋值或方法调用。

The JLS classifies those expressions which are allowed as a standalone statement as StatementExpression : JLS将允许作为独立语句的表达式分类为StatementExpression

Assignment 分配
PreIncrementExpression PreIncrementExpression
PreDecrementExpression PreDecrementExpression
PostIncrementExpression PostIncrementExpression
PostDecrementExpression PostDecrementExpression
MethodInvocation 的MethodInvocation
ClassInstanceCreationExpression ClassInstanceCreationExpression

There are a couple of obscure ways to use the ternary here anyway: 无论如何,有几种不明确的方法可以在这里使用三元组:

// statement is an assignment
boolean ignored =
    Character.isDigit(...) ?
        digitArrayList.add(myDto) : charArrayList.add(myDto);

// statement is a method invocation
(Character.isDigit(...) ? digitArrayList : charArrayList)
    .add(myDto);

But I don't recommend using those, they are really just a curiosity. 但我不建议使用它们,它们只是一种好奇心。 It's more clear to just use the if...else . 更简单的是使用if...else

The fundamental purpose of the ternary operator is to compress multiple lines if..else condition into single line. 三元运算符的基本目的是将多条线压缩,如果...条件为单线。 So that it increases the readability of the code. 这样就增加了代码的可读性。 The ternary operator is also known as conditional assignment operator, so here if you are not assigning the value. 三元运算符也称为条件赋值运算符,因此,如果您没有赋值,则在此处。 So it gives the error. 所以它给出了错误。

To make your code work with ternary operator, you can modify the code like below 要使代码与三元运算符一起使用,您可以修改如下代码

boolean result =  Character.isDigit(myDto.getNameStr().charAt(0)) ? digitArrayList.add(myDto) : charArrayList.add(myDto);

The best practice is to divide this kind of code into if...else code block 最佳实践是将此类代码划分为if ... else代码块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM