在 Java 中使用三元运算符进行流量控制
Use ternary operator for flow control in Java
可以使用 ?:
(三元)运算符代替 if-then-else 语句进行赋值,但也可以以某种方式用于流控制?例如,
flag ? method1 : method2;
是的,但是:
您必须保存结果;你不能只有一个表达式(在 Java 中;你可以在其他一些语言中)。
方法不能有 void
return 类型。
条件表达式的类型将取决于您使用的方法的 return 类型。如果两者都是 return 布尔值,则类型将为布尔值;如果两者都是数字,则结果将是数字;否则,结果将是引用类型(例如 Object
)。
例如:
x = flag ? method1() : method2();
JLS §15.25 - Conditional Operator ?
:
中的更多内容。
如果能够以这种方式使用条件语句对您很重要(就个人而言,我会坚持使用流程控制语句),您可以定义一个如下所示的实用程序方法:
static void consume(Object o) {
}
然后:
consume(flag ? method1() : method2());
可能已经回答了。但是,是的,如果两个方法都返回相同的类型,我们可以在三元运算中使用这些方法。示例如下。
public static void main(String[] args) {
boolean b = true;
int i = b ? getThis() : getThat();
}
public static int getThis() {
return 1;
}
public static int getThat() {
return 2;
}
您可以使用它,但它应该是相同的(可能在转换后)return类型请参阅 JLS 15.25. Conditional Operator ? : 了解更多详细信息:
This conversion may include boxing or unboxing conversion (§5.1.7, §5.1.8)
可以使用 ?:
(三元)运算符代替 if-then-else 语句进行赋值,但也可以以某种方式用于流控制?例如,
flag ? method1 : method2;
是的,但是:
您必须保存结果;你不能只有一个表达式(在 Java 中;你可以在其他一些语言中)。
方法不能有
void
return 类型。
条件表达式的类型将取决于您使用的方法的 return 类型。如果两者都是 return 布尔值,则类型将为布尔值;如果两者都是数字,则结果将是数字;否则,结果将是引用类型(例如 Object
)。
例如:
x = flag ? method1() : method2();
JLS §15.25 - Conditional Operator ?
:
中的更多内容。
如果能够以这种方式使用条件语句对您很重要(就个人而言,我会坚持使用流程控制语句),您可以定义一个如下所示的实用程序方法:
static void consume(Object o) {
}
然后:
consume(flag ? method1() : method2());
可能已经回答了。但是,是的,如果两个方法都返回相同的类型,我们可以在三元运算中使用这些方法。示例如下。
public static void main(String[] args) {
boolean b = true;
int i = b ? getThis() : getThat();
}
public static int getThis() {
return 1;
}
public static int getThat() {
return 2;
}
您可以使用它,但它应该是相同的(可能在转换后)return类型请参阅 JLS 15.25. Conditional Operator ? : 了解更多详细信息:
This conversion may include boxing or unboxing conversion (§5.1.7, §5.1.8)