Python 官方文档:入门教程 => 点击学习
目录前言 方案一: 数组 方案二:HashMap 由 key 获取 value 由 value 获取 key 解决方案三:枚举 总结 前言 开发系统一些状态,比如订单状态:数据库存
开发系统一些状态,比如订单状态:数据库存储是数字或字母,但是需要显示中文或英文,一般用到if-else代码判断,但这种判断可读性比较差,也会影响后期维护,也比较容易出现bug。比如:
假设状态对应关系:1:agree 2:refuse 3:finish
int status;
String statusStr = null;
if (status == 1) {
status = "agree";
} else if (status == 2) {
status = "refuse";
}else if(status == 3) {
status = “finish”;
}
这种仅限通过数字获取到字母或者中文。
首先设置数组
String[] statusArray = {"","agree","refuse","finish"};
通过数组的位置获取数组的值
int status;
String statusStr = statusArray[status];
创建和添加map:
private static final Map<Integer,String> map = new HashMap<>();
static {
map.put(1,"agree");
map.put(2,"refuse");
map.put(3,"finish");
}
这种有两种求解方式,通过 key 获取 value 以及通过 value 获取 key,
直接使用 get 方法即可。这里的key相对于数组解法,不限制 key 的类型。
int status;
map.get(status);
使用map遍历:
int status;
for(Map.Entry<Integer, String> vo : map.entrySet()){
if (vo.getValue().equals(result)) {
status = vo.geTKEy();
break;
}
}
先定义一个枚举类
public enum TestEum {
agree(1,"agree"),
refuse(2,"refuse");
private int code;
private String capation;
TestEum(int code,String capation){
this.code = code;
this.capation = capation;
}
public int getCode() {
return code;
}
public String getCapation() {
return capation;
}
String of(int code){
for (TestEum testEum : TestEum.values()) {
if (testEum.getCode() == code) {
return testEum.getCapation();
}
}
return null;
}
}
有了枚举以后,if-else 代码块可以优化成一行代码
String statusStr = TestEum.of(status);
到此这篇关于Java优化if-else代码的文章就介绍到这了,更多相关Java优化if-else代码内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java优化if-else代码的实战记录
本文链接: https://www.lsjlt.com/news/135938.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0