三元运算符 - JAVA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25163713/
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-10 23:45:55  来源:igfitidea点击:

Ternary Operator - JAVA

javaternary-operator

提问by Lucas Pugliese

Is it possible to change this:

是否有可能改变这一点:

if(String!= null) {

    callFunction(parameters);

} else {

    // Intentionally left blank

}

...to a ternary operator?

...对于三元运算符?

回答by Suresh Atta

Yes. You can with keeping same nullin elseblock.

是的。您可以nullelse块中保持相同。

String result = str !=null ?  callFunction(parameters) : null;

Make sure that callFunction(parameters)return a String.

确保callFunction(parameters)返回一个String.

回答by msrd0

It could be possible if your method callFunction()has a return type. Then, you could do it like SURESH ATTAwrote in his answer:

如果您的方法callFunction()具有返回类型,则有可能。然后,你可以像SURESH ATTA在他的回答中写的那样:

String result = str!=null ? callFunction(str) : null;

Or with any other type for result or any other arguments. If you want to call a method in the else-Statement too, this one needs to have the same return type as the one in your if-statement.

或者使用任何其他类型的结果或任何其他参数。如果您也想调用else-Statement 中的方法,则此方法需要与-statement 中的方法具有相同的返回类型if

If your method doesn't have a return type / the return type of callFunction()is void, it is not possible to change your if-else-statement into a ternary operator.

如果您的方法没有返回类型/ callFunction()is的返回类型,则void无法将您的if--else语句更改为三元运算符。

回答by Christopher Rucinski

Well, the ternary operatorin Java acts like this...

好吧,ternary operatorJava 中的行为是这样的......

return_value = (true-false condition) ? (if true expression) : (if false expression);

...Another way of looking at it...

......另一种看待它的方式......

return_value = (true-false condition) 
             ? (if true expression) 
             : (if false expression);


You question is kind of vague and we have to assume here.

你的问题有点模糊,我们必须在这里假设。

  • If (and only if)callFunction(...)declares a non-voidreturn value (Object, String, int, double, etc..) - it seems like it does not do that via your code -then you could do this...

    return_value = (string != null) 
                 ? (callFunction(...)) 
                 : (null);
    
  • If callFunction(...)does not return a value, then you cannotuse the ternary operator! Simple as that. You will be using something that you don't need.

    • Please post more code to clear up any issues
  • 如果(且仅当)callFunction(...)声明了一个non-void返回值(Object, String, int, double, 等等)——它似乎不是通过你的代码做到的——那么你可以这样做......

    return_value = (string != null) 
                 ? (callFunction(...)) 
                 : (null);
    
  • 如果callFunction(...)没有返回值,则不能使用三元运算符!就那么简单。您将使用不需要的东西。

    • 请发布更多代码以解决任何问题


Nonetheless, ternary operator should represent alternative assignments only!!Your code does not seem to do that, so you should not be doing that.

尽管如此,三元运算符应该只代表替代赋值!!您的代码似乎没有这样做,所以您不应该这样做。

This is how they should work...

这就是他们应该如何工作...

if (obj != null) {            // If-else statement

    retVal = obj.getValue();  // One alternative assignment for retVal

} else {

    retVal = "";              // Second alternative assignment for retVale

}

This can be converted to...

这可以转换为...

retVal = (obj != null)
       ? (obj.getValue())
       : ("");


Since it seems like you mightbe trying to just refactor this code to be a one-liner, I have added the following

由于看起来您可能只是试图将此代码重构为单行代码,因此我添加了以下内容

Also, if your false-clause is truely empty, then you can do this...

另外,如果你的 false-clause 真的是空的,那么你可以这样做......

if (string != null) {

    callFunction(...);

} // Take note that there is not false clause because it isn't needed

OR

或者

if (string != null) callFunction(...);  // One-liner

回答by Holger

The ternary operator can be used to combine two expressionsbut an empty statementis not an expression.

三元运算符可用于组合两个表达式,但空语句不是表达式。

A method invocation can be used as an expression if the method returns a value (read: is not declared void) and it could be used together with a dummy constant nullto form a ternary operator but the result would be again an expression which is not allowed in places where a statementis required, in other words, it can not replace an ifstatement.

如果方法返回一个值(读取:未声明void),则方法调用可以用作表达式,并且它可以与虚拟常量一起使用null以形成三元运算符,但结果将再次成为不允许的表达式需要声明的地方,换句话说,它不能代替if声明。

By adding another construct taking an expression and imposing no additional side effect you can construct a complete replacement. E.g. by declaring and assigning a new, otherwise unused, local variable you get:

通过添加另一个带有表达式的构造并且不施加额外的副作用,您可以构造一个完整的替换。例如,通过声明和分配一个新的,否则未使用的局部变量,您会得到:

Object dummy=condition? callFunction(parameters): null;

But there is no benefit over simply saying if(condition) callFunction(parameters);. It might even add unnecessary overhead as it will perform auto-boxing if the return value is a primitive type.

但是简单地说没有任何好处if(condition) callFunction(parameters);。它甚至可能会增加不必要的开销,因为如果返回值是原始类型,它将执行自动装箱。

With Java?8 there is a solution to the puzzle that works even for voidmethods:

使用 Java?8 有一个解决这个难题的void方法,它甚至适用于方法:

((Runnable)(condition? ()->callFunction(parameters): ()->{})).run();

but it still has no advantage over simply using if.

但与简单地使用if.