gpt4 book ai didi

java枚举类常见操作

转载 作者:知者 更新时间:2024-03-13 08:21:53 26 4
gpt4 key购买 nike

java枚举类常见操作

public enum Status {
    OK(0, "成功"),
    ERROR_A(100, "错误A"),
    ERROR_B(200, "错误B");

    Status(int number, String description) {
        this.code = number;
        this.description = description;
    }
    private int code;
    private String description;
    public int getCode() {
        return code;
    }
    public String getDescription() {
        return description;
    }
    //根据code查找description
    public static String getValue(int v) { 
        for (Status s : Status.values()) {
            if (v==s.getCode()){
              return  s.getDescription();
            }
        }
        return "";
    }
    
    //判断Status里是否有此code
    public static boolean isInclude(String co) {
        for (OpenBusinessEnum s : OpenBusinessEnum.values()) {
           if (co.equals(s.getCode())){
               return  true;
           }
       }
       return false;
    }
    
    //获取所有的description
    public static String[] getValue() { 
       String[] arry = new String[Status.values().length];
       int i = 0;
       for (Status s : Status.values()) {
           arry[i] = s.getDescription();
           i++;
       }
       return arry;
   }

	//判断该枚举中是否含有传入的值
    public static boolean contains(String test) {
        for (Status c : Status.values()) {
            if (c.name().equals(test)) {
                return true;
            }
        }
        return false;
    }
}

测试

System.out.println(Status.getde(0));//查找Status枚举中code是0的description的值。输出:成功
 System.out.println(Status.valueOf("OK").getCode());//查找Status枚举中OK的code。输出:0
 System.out.println(Status.valueOf("OK").getDescription());//查找Status枚举中OK的description。输出:成功

System.out.println(Status.OK); //输出:OK
System.out.println(Status.OK.getCode()); //输出:0
System.out.println(Status.OK.getDescription()); //输出:成功
System.out.println(Arrays.asList(Status.getde()));//输出:[成功, 错误A, 错误B]

String event1 = "aaa";
String event2 = "ERROR_B";
System.out.println(Status.contains(event1));//false。因为Status中不含有aaa
System.out.println(Status.contains(event2));//true。因为Status中含有ERROR_B

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com