java中过多if-else分支语句的优化方案
利用Map优化过的的if-else分支
package com.taiping.test;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) throws Exception {
int seatCount=2; //需要进行判断的变量
String projectCode;//判断之后赋值的变量
String type = "A";
/**优化之前,逻辑判断太多,效率低下*/
if(type.equals("A")){
if(seatCount == 2){
projectCode = "0001";
}else if(seatCount == 4){
projectCode = "0002";
}else if(seatCount == 5){
projectCode = "0003";
}else if(seatCount == 6){
projectCode = "0004";
}else if(seatCount == 7){
projectCode = "0005";
}
}else{
if(seatCount == 2){
projectCode = "0006";
}else if(seatCount == 4){
projectCode = "0007";
}else if(seatCount == 5){
projectCode = "0008";
}else if(seatCount == 6){
projectCode = "0008";
}else if(seatCount == 7){
projectCode = "0010";
}
}
/**优化之后,采用map方式,简洁高效*/
Map<Integer, String> map = new HashMap<Integer, String>();
if(type.equals("A")){
map.put(2, "0001");
map.put(4, "0002");
map.put(5, "0003");
map.put(6, "0004");
map.put(7, "0005");
}else{
map.put(2, "0006");
map.put(4, "0007");
map.put(5, "0008");
map.put(6, "0009");
map.put(7, "0010");
}
projectCode = map.get(seatCount);//采用map的get方式取值
System.out.println(projectCode);
//优化前与优化后结果一致,map方式效率更好
}
}