java - Java8枚举避免多个if else
问题描述
在 java 8 中,是否有任何选项可以避免多个 if else 检查枚举值并执行特定操作。我不喜欢使用下面的例子吗?
if enum equals A
PRINT A
else if enum equals B
PRINT B
else if enum equlas C
PRINT C
解决方案
您正在寻找的是switch
陈述。不仅在 Java 8 中,您还可以enums
在所有以前的 Java 版本中打开。考虑以下代码:
public class Dummy {
enum MyENUM {
A,
B,
C
}
public static void main(final String[] args) {
MyENUM myENUM = MyENUM.A;
switch (myENUM) {
case A:
System.out.println(MyENUM.A);
break;
case B:
System.out.println(MyENUM.B);
break;
case C:
System.out.println(MyENUM.C);
break;
}
}
}
如果您不想使用switch
语句,此页面提供了switch
语句的各种替代方案。
替换的方法之一switch
是创建地图。考虑下面的例子:
public static void main(final String[] args) {
Map<MyENUM,Runnable> map = new HashMap<>();
map.put(MyENUM.A,() -> System.out.println(MyENUM.A));
map.put(MyENUM.B,() -> System.out.println(MyENUM.B));
map.put(MyENUM.C,() -> System.out.println(MyENUM.C));
MyENUM myENUM = MyENUM.A;
map.get(myENUM).run();
}
产生以下结果:
A
推荐阅读
- java - 使用硬连线到代码中的用户名和密码在 Spring Security 中进行身份验证的过程
- c# - 如何为地图坐标实现 IEnumerator?
- java - notifyItemChanged(int position) 仅更新 Recyclerview 中的单个项目
- javascript - CSS 窗帘,网站运行时会打开
- macos - Pyusb 和 Libusb 在 MacOS 上提供 NoBackendError
- python - 未找到超参数优化 Python 中的 Leaky ReLU
- c - C alloc / free struct arr
- c# - C#方法或对象不能被第二次调用
- javascript - 使用水平滚动处理溢出内容
- python - 我想使用类和数据结构创建一个简单的库存管理系统。我是 python 中的 OOP 新手