java - Java 中是否有类似于 PHP 的三元运算符的简短版本?

标签 java php ternary-operator

在 PHP 中,三元运算符有一个简短的版本。

expr1 ? expr2 : expr3;

变成

expr1 ? : expr3;

短版本返回 expr1 的结果为真,expr3 为假。 这允许很酷的代码可以根据自己的当前状态填充变量。例如:

$employee = $employee ? : new Employee();

如果 $employee == null 或由于任何其他原因计算为 false,上面的代码将创建一个 new Employee(); 否则 中的值$employee 将被重新分配给自己。

我在 Java 中寻找类似的东西,但找不到三元运算符的任何类似用例。所以我问是否有这样的功能或类似的东西可以避免三元运算符的表达式之一以减少重复。

最佳答案

不,没有。 (三元运算需要 by definition 三个操作数)

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

来源:The PHP Manual

就像 Java 中的一样,但在 Java 中您需要指定两种结果:

The ternary if-else operator works with three operands producing a value depending on the truth or falsehood of a boolean assertion. It's form is as follows:-

boolean-exp ? value1 : value2

来源:

Java specs on the ternary conditional operator

Official Java documentation

The Java.net Blogs

另外请记住,与 Java 和其他所有具有类似运算符的流行语言不同,?: 在 PHP 中是左关联的。所以这个:

<?php
$arg = "T";
$vehicle = ( ( $arg == 'B' ) ? 'bus' : 
             ( $arg == 'A' ) ? 'airplane' : 
         ( $arg == 'T' ) ? 'train' : 
         ( $arg == 'C' ) ? 'car' : 
         ( $arg == 'H' ) ? 'horse' : 
                               'feet' );
echo $vehicle;

打印 horse 而不是 train(这是您在 Java 中所期望的)

来源:

http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/#operators

关于java - Java 中是否有类似于 PHP 的三元运算符的简短版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27387777/

相关文章:

java - 服务一结束,通知就会消失

java - 在 Java 中无法获得所需的 XML 输出

grails - 使用三元运算符的Grails hasErrors方法?

javascript - AngularJS:三元运算符条件检查中的函数调用

Java 11 应用程序作为轻量级 docker 镜像

java - ThreadPoolExecutor参数配置

java - 将json关联数组插入mysql

php - 下拉数据未发送到 $_POST php

php - 确保 PHP 中的有效 UTF-8

Python 不能使用三元运算符在列表理解中使用解包