Java 中 Switch Case 的替代方案

Alternative to Switch Case in Java(Java 中 Switch Case 的替代方案)

本文介绍了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 的替代方案

基础教程推荐