关于java:Java优化ifelse代码

0次阅读

共计 1323 个字符,预计需要花费 4 分钟才能阅读完成。

前言

开发零碎一些状态,比方订单状态:数据库存储是数字或字母,然而须要显示中文或英文, 个别用到 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];

长处:占用内存少
毛病:状态值只能是数字,而且还须要思考数组越界状况

计划二:HashMap

创立和增加 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,

由 key 获取 value

间接应用 get 办法即可。这里的 key 绝对于数组解法,不限度 key 的类型。

int status;
map.get(status);

由 value 获取 key

应用 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);

总结

  1. 如果通过数字获取形容,应用数组即可。
  2. 如果通过形容获取数字,应用枚举和 HashMap 都能够。
正文完
 0