Some status of the development system, such as order status: the database storage is numbers or letters, but it needs to display Chinese or English. Generally, if-else code is used to judge, but this judgment is relatively poor in readability and will also affect later maintenance. Prone to bugs. for example:
Assume the corresponding state of the relationship: 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”;
}
This is limited to obtaining letters or Chinese through numbers.
First set the array
String[] statusArray = {"","agree","refuse","finish"};
Get the value of the array by the position of the array
int status;
String statusStr = statusArray[status];
Advantages: occupies less memory
Disadvantages: The state value can only be a number, but also need to consider the array out of bounds situation
Create and add map:
private static final Map<Integer,String> map = new HashMap<>();
static {
map.put(1,"agree");
map.put(2,"refuse");
map.put(3,"finish");
}
There are two ways to solve this, get value by key and get key by value,
Just use the get method. The key here is relative to the array solution and does not limit the type of key.
int status;
map.get(status);
Use map to traverse:
int status;
for(Map.Entry<Integer, String> vo : map.entrySet()){
if (vo.getValue().equals(result)) {
status = vo.getKey();
break;
}
}
Advantages: the status value does not limit the number
Disadvantages: take up a lot of space
First define an enumeration class
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;
}
}
With enumeration, the if-else code block can be optimized into one line of code
String statusStr = TestEum.of(status);
If you get the description by number, just use an array.
If you get the number by description, you can use enumeration and HashMap.