[英]Java - Switch Label with parentheses
I found that parentheses can be used in switch label, eg:我发现在开关label中可以使用括号,例如:
switch(id) {
case (CONSTANT):
case (1):
// Do action
break;
}
But why Java allow parentheses in this case, is there a use case?但是为什么Java在这种情况下允许括号,有用例吗? because I can't use
||
因为我不能用
||
or ,
to use multiple, eg或
,
使用多个,例如
case (CONSTANT||1):
case (CONSTANT,1):
So why allow this syntax, I didn't find in JLS :那么为什么允许这种语法,我在JLS中没有找到:
SwitchLabel: case ConstantExpression: case EnumConstantName: default: EnumConstantName: Identifier
Well, a ConstantExpression can contain parentheses:好吧, ConstantExpression可以包含括号:
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
常量表达式是表示原始类型值或字符串的表达式,它不会突然完成并且仅使用以下内容组成:
...
...
Parenthesized expressions (§15.8.5) whose contained expression is a constant expression.
带括号的表达式(第 15.8.5 节),其包含的表达式是常量表达式。
...
...
Hence, since any constant expression (whose type is char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type) is allowed after case
, parentheses are allowed.因此,由于在
case
之后允许使用任何常量表达式(其类型为 char、byte、short、int、Character、Byte、Short、Integer、String 或枚举类型),因此允许使用括号。
The case just needs to be a constant expression. case 只需要是一个常量表达式。 Something in parenthesis may be a constant expression.
括号中的内容可能是一个常量表达式。
private static final int TWO = 2;
public static void main(String[] args) {
foo(3);
foo(9);
}
private static void foo(int i) {
switch (i) {
case (TWO + 1):
System.out.println("a");
break;
case (TWO + 1) * 3:
System.out.println("b");
break;
}
}
CONSTANT || 1
CONSTANT || 1
is not allowed because integers are not valid operands of ||
CONSTANT || 1
是不允许的,因为整数不是||
的有效操作数. .
The comma syntax is not a thing.逗号语法不是一回事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.