何时在 Java 中使用 switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2103080/
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
When to use a switch statement in Java
提问by Dan
I appreciate that anything that can be done by a switch statment, can be done by an if else statement.
我很欣赏可以通过 switch 语句完成的任何事情,都可以通过 if else 语句完成。
But are there stylistic rules for when one should use the switch rather than if else statment.
但是是否有什么时候应该使用 switch 而不是 if else 语句的风格规则。
采纳答案by Joey
Well, switch
feels "lighter" in many cases than an if
/else if
ladder, in my opinion. Basically you don't have that much syntax with braces and parentheses in the way of your code. That being said, switch
inherits C's syntax. That means you have break
and only a single scope for variables unless you introduce new blocks.
嗯,在我看来,在switch
很多情况下感觉比if
/else if
梯子“更轻” 。基本上,您的代码中没有那么多带有大括号和圆括号的语法。也就是说,switch
继承了 C 的语法。这意味着break
除非您引入新块,否则您只有一个变量作用域。
Still, the compiler is able to optimize switch
statements into a lookup table and perform compile-time checking for literals when dealing with enumerations. So, I'd suggest that it's usually preferable to use switch
over if
/else if
if you're dealing with numeric or enum types.
尽管如此,编译器仍然能够将switch
语句优化到查找表中,并在处理枚举时对文字执行编译时检查。因此,我建议通常最好使用switch
over if
/else if
如果您正在处理数字或枚举类型。
回答by danben
You use a switch statement when you are switching on different values of primitive / enum / wrapper types. (And not all primitive / wrapper types, just the supported ones - byte, short, char, int).
当您切换原始/枚举/包装类型的不同值时,您可以使用 switch 语句。(并不是所有的原始/包装类型,只是支持的类型 - byte、short、char、int)。
If/else handles the rest.
If/else 处理其余的。
For instance, it is more aesthetically pleasing to say:
例如,更美观地说:
int i = getValueOfI();
switch (i) {
case 1:
// do something
break;
case 2:
// do something
break;
etc.
等等。
than
比
if (i == 1) {
} else if (i == 2) {
}...
for a large number of cases. But you can't switch on Strings, or function values, or complex conditions, so if you need to do any of that then you're stuck with if/else.
对于大量的情况。但是你不能打开字符串、函数值或复杂条件,所以如果你需要做任何这些,那么你就会被 if/else 困住。
回答by Larry Watanabe
first of all, the switch statement has to be useable. If the switch is based on the value of a variable, then it can be used. If it is based on a complex AND/OR/NOT boolean expression that varies for each condition, then you can't use it at all.
首先,switch 语句必须可用。如果开关是基于一个变量的值,那么它可以被使用。如果它基于复杂的 AND/OR/NOT 布尔表达式,该表达式因每个条件而异,那么您根本无法使用它。
That being said, if it is applicable, and there are at least 2 cases, then I use the switch. It is more easily extendible, easier to read and check.
话虽如此,如果适用,并且至少有两种情况,那么我使用开关。它更易于扩展,更易于阅读和检查。
回答by GuruKulki
if you have too many conditions to check of a similar type u can go for switch.
如果您有太多条件要检查类似类型,您可以切换。
回答by Otávio Décio
As with other languages such as C or C++, switch statements are useful when you want to compare a given variable with a list of possible values and perform an action depending on these values. It is terser than if else statements.
与其他语言(例如 C 或 C++)一样,当您想要将给定变量与可能值列表进行比较并根据这些值执行操作时,switch 语句非常有用。它比 if else 语句简洁。
回答by bertolami
I use switch statements for enums, it is more readable that a if else if else if statements. However, you should try to avoid such checks in a OO design.
我对枚举使用 switch 语句,它比 if else if else if 语句更具可读性。但是,您应该尽量避免在 OO 设计中进行此类检查。
回答by Alex Ntousias
There are two factors for me:
对我来说有两个因素:
Readability and whether you want to decide something using ranges of values or conditions (in switch statements you can only use a single integer or enumerated value).
可读性以及是否要使用值范围或条件来决定某些事情(在 switch 语句中,您只能使用单个整数或枚举值)。
回答by Riduidel
Personnally, i use to find both constructs a little too procedural. Although it may considered as OO extermism, I use to use a Map containing instances of an internal interface for each cases of the if. It allows better code isolation, i think. However, to trully reply your question, I only use switchs when I have cases that really overlap (the, I don't use break statements). Unfortunatly, it's really not a maintainable code block.
就我个人而言,我过去常常发现这两种结构都过于程序化。虽然它可能被认为是面向对象的极端主义,但我习惯于使用包含内部接口实例的 Map 来处理 if 的每种情况。我认为它允许更好的代码隔离。但是,要真正回答您的问题,我仅在遇到真正重叠的情况时才使用开关(我不使用 break 语句)。不幸的是,它真的不是一个可维护的代码块。
回答by deamon
Switch has two relevant disadvantages:
Switch 有两个相关的缺点:
- it is limited to primitive types and enums
- you have to remember "break", what could lead to not so obvious bugs
- 它仅限于原始类型和枚举
- 你必须记住“break”,什么会导致不那么明显的错误
Often switch is a sign for poor OO design, because you'd better use polymorphism.
通常 switch 是糟糕的 OO 设计的标志,因为你最好使用多态。
The only possible advantage of switch is, that it is more readable. But is
switch 唯一可能的优点是,它更具可读性。但是
switch (i) {
case 1:
// do something
break;
case 2:
// do something
break;
}
more readable than this:
比这更具可读性:
if (i == 1)
//do something
else if (i == 2)
// do something else
I'd say: no! And you wouldn't have the disadvantages of switch.
我会说:不!而且你不会有 switch 的缺点。
My suggestion: Try to avoid switch.
我的建议:尽量避免切换。
回答by Armstrongest
Switch has one advantage when it comes to clarity:
在清晰度方面,Switch 有一个优势:
switch (i) {
case 1:
// do something
break;
case 2:
case 4:
// do something
break;
case 5:
// do something
break;
}
If the code for 2 and 4 are identical, it may be more clear than:
如果 2 和 4 的代码相同,则可能比:
if ( i == 1 ) {
// do something
}
if ( (i == 2) || (i == 4) ) {
// do something
}
if ( (i == 5 ) {
// do something
}
It's also easier for you (or another programmer) to split out the 2and 4cases.
您(或其他程序员)也更容易将2和4情况分开。