Java switch语句多种情况
只是想弄清楚如何在 Java switch 语句中使用多种情况。这是我想做的一个例子:
switch (variable)
{
case 5..100:
doSomething();
break;
}
与必须做的事情相比:
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
如果可能的话有什么想法,或者什么是好的替代方案?
Just trying to figure out how to use many multiple cases for a Java switch statement. Here's an example of what I'm trying to do:
switch (variable)
{
case 5..100:
doSomething();
break;
}
versus having to do:
switch (variable)
{
case 5:
case 6:
etc.
case 100:
doSomething();
break;
}
Any ideas if this possible, or what a good alternative is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
第二种选择完全没问题。我不知道为什么回复者说这是不可能的。这很好,我一直这样做:
The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:
遗憾的是,这在 Java 中是不可能的。您必须求助于使用
if-else
语句。Sadly, it's not possible in Java. You'll have to resort to using
if-else
statements.输出:
Src:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/ switch.html
Out:
Src: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
也许不像以前的一些答案那么优雅,但是如果您想实现具有几个大范围的开关案例,只需预先将范围组合到单个案例中即可:
Maybe not as elegant as some previous answers, but if you want to achieve switch cases with few large ranges, just combine ranges to a single case beforehand:
这可以通过 Java 14 中的开关增强功能实现。以下是一个相当直观的示例,说明如何实现相同的目标。
This is possible with switch enhancements in Java 14. Following is a fairly intuitive example of how the same can be achieved.
替换过大的
switch
和if/else
构造的一种面向对象选项是使用责任链模式
来对决策进行建模。责任链模式
这是一个使用泛型也是类型安全的示例实现。
这只是我在几分钟内快速完成的稻草人,更复杂的实现可能允许将某种
命令模式
注入到Case
实现实例中使其更像回调 IoC 风格。这种方法的好处是 Switch/Case 语句都是关于副作用的,这将副作用封装在类中,以便可以更好地管理和重用它们,它最终更像是函数式语言中的模式匹配,这并不是一件坏事。
我将发布对此的任何更新或增强要点。
One Object Oriented option to replace excessively large
switch
andif/else
constructs is to use aChain of Responsibility Pattern
to model the decision making.Chain of Responsibility Pattern
Here is an example implementation that is also Type Safe using Generics.
This is just a quick straw man that I whipped up in a few minutes, a more sophisticated implementation might allow for some kind of
Command Pattern
to be injected into theCase
implementations instances to make it more of a call back IoC style.Once nice thing about this approach is that Switch/Case statements are all about side affects, this encapsulates the side effects in Classes so they can be managed, and re-used better, it ends up being more like Pattern Matching in a Functional language and that isn't a bad thing.
I will post any updates or enhancements to this Gist on Github.
根据这个问题,这是完全有可能的。
只需将包含相同逻辑的所有 case 放在一起,不要将
break
放在它们后面。这是因为没有
break
的case
会跳转到另一个case
,直到break
或return
。编辑:
回复评论,如果我们确实有 95 个具有相同逻辑的值,但具有不同逻辑的情况数量较少,我们可以这样做:
如果您需要更好的控制,
if-else
就是选择。According to this question, it's totally possible.
Just put all cases that contain the same logic together, and don't put
break
behind them.It's because
case
withoutbreak
will jump to anothercase
untilbreak
orreturn
.EDIT:
Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:
If you need finer control,
if-else
is the choice.JDK-13 和 JEP 354:切换表达式(预览版) a href="https://openjdk.java.net/jeps/361" rel="noreferrer">JEP 361:JDK-14 中的 Switch 表达式(标准) 将扩展switch 语句,因此它可以用作表达式。
现在您可以:
case L ->
):<块引用>
“case L ->”右侧的代码switch 标签仅限于表达式、块或(为方便起见)抛出语句。
<块引用>
要从 switch 表达式中生成值,需要删除
break
with value 语句,而代之以yield
语句。开关表达式示例:
JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.
Now you can:
case L ->
):Switch expression example:
从最新的 java-12 版本开始,预览语言功能中提供了同一 case 标签中的多个常量
它看起来像:
查看更多JEP 325:切换表达式(预览版)
From the last java-12 release multiple constants in the same case label is available in preview language feature
It looks like:
See more JEP 325: Switch Expressions (Preview)
基本上:
如果您确实需要使用开关,那是因为您需要在某些范围内执行各种操作。在这种情况下,是的,您将得到混乱的代码,因为事情变得越来越复杂,只有遵循模式的东西才能很好地压缩。
使用开关的唯一原因是,如果您只是测试数字开关值,则可以节省键入变量名称的时间。你不会打开 100 个东西,它们也不会都做同样的事情。这听起来更像是一个“如果”块。
Basically:
If you really needed to use a switch, it would be because you need to do various things for certain ranges. In that case, yes, you're going to have messy code, because things are getting complex and only things which follow patterns are going to compress well.
The only reason for a switch is to save on typing the variable name if you're just testing for numeric switching values. You aren't going to switch on 100 things, and they aren't going to be all doing the same thing. That sounds more like an 'if' chunk.
// 不合规代码示例
// 合规解决方案
// Noncompliant Code Example
//Compliant Solution
可以使用 Vavr 库来处理这个问题
这当然只是轻微的改进,因为所有情况仍需明确列出。但定义自定义谓词很容易:
Match 是一个表达式,因此这里它返回类似 Runnable 实例的内容,而不是直接调用方法。匹配完成后,可以执行
Runnable
。有关更多详细信息,请参阅官方文档。
It is possible to handle this using Vavr library
This is of course only slight improvement since all cases still need to be listed explicitly. But it is easy to define custom predicate:
Match is an expression so here it returns something like
Runnable
instance instead of invoking methods directly. After match is performedRunnable
can be executed.For further details please see official documentation.
不使用硬编码值的一种替代方法是在 switch 语句上使用范围映射:
One alternative instead of using hard-coded values could be using range mappings on the the switch statement instead:
作为替代方案,您可以使用如下所示:
或者以下代码也适用
for alternative you can use as below:
or the following code also works
JEP 427:switch 的模式匹配(第三个预览版) 作为 Java 19 中的预览功能,并允许您使用所谓的“受保护的模式”解决问题:
热启用 Java 中的预览功能,请参阅 这个SO问题。
到 Java 20 或 21,此语法可能会作为标准功能提供。
JEP 427: Pattern Matching for switch (Third Preview) arrived as a preview feature in Java 19, and allows you to solve the problem with a so called "guarded patten":
Hot to enable preview Features in your Java, see this SO-Question.
By Java 20 or 21, this syntax will probably be available as a standard feature.
我找到了这个问题的解决方案...我们可以在java中的switch case中使用多个条件..但它需要多个switch case..
I found a solution to this problem... We can use multiple conditions in switch cases in java.. but it require multiple switch cases..