Alternative to Switch Case in Java(Java 中 Switch Case 的替代方案)
问题描述
除了看起来不太好的 if else 之外,还有其他方法可以在 Java 中实现 switch case.一组值会组合在一起,根据选择需要执行相应的方法.
Is there any alternative way to implement a switch case in Java other than if else which is not looking good. A set of values will be there in combination, according to the selection corresponding method has to be executed.
推荐答案
大概你正在努力满足 case 保持不变的要求.通常这是一种代码气味,但您可以做一些事情.您可能想提出并链接到另一个详细说明您尝试转换的问题的问题.
Presumably you're struggling with the requirement of case's being constant. Typically this is a code-smell, but there are things you can do. You might want to raise and link to another question that details why you're trying to switch.
Map<String,Object> map = new HasMap<String,Object>();
// ... insert stuff into map
// eg: map.add("something", new MyObject());
String key = "something";
if (map.contains(key)) {
Object o = map.get(key);
}
在上面的示例中,您可能希望映射到处理程序",例如
In the example above, you might want to map to 'handlers', something like
interface Handler {
public void doSomething();
}
然后这一切都变成了查找.
which then makes this all turn into a lookup.
if (map.contains(key)) { map.get(key).doSomething(); }
再次,它有点味道,所以请发布一个说明推理的问题.
Again, it's a bit of a smell, so please post a question which illustrates the reasoning.
这篇关于Java 中 Switch Case 的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 中 Switch Case 的替代方案
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01