Java优化if-else代码

2021年09月15日 阅读数：4

前言

``````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];
``````

方案二:HashMap

``````    private static final Map<Integer,String> map = new HashMap<>();

static {
map.put(1,"agree");
map.put(2,"refuse");
map.put(3,"finish");
}
``````

由 key 获取 value

``````int status;
map.get(status);``````

由 value 获取 key

``````int status;
for(Map.Entry<Integer, String> vo : map.entrySet()){
if (vo.getValue().equals(result)) {
status = vo.getKey();
break;
}
}``````

解决方案3、枚举

``````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;
}
}
``````

``String statusStr = TestEum.of(status);``

总结

1. 若是经过数字获取描述，使用数组便可。
2. 若是经过描述获取数字，使用枚举和HashMap均可以。