java 枚举类

参考文章

基础使用

public enum Color {
    RED, GREEN, BLUE; //枚举常量“实例”,如果后面有内容,用分号结束
    public static void main(String[] args) {
        System.out.println("=========== Print all Color ===========");
        for (Color c : Color.values()) {        //遍历
            System.out.println(c + " ordinal: " + c.ordinal());     //默认生成声明时的次序
        }
        Color green = Color.GREEN;
        System.out.println("green name(): " + green.name());
        System.out.println("green getDeclaringClass(): " + green.getDeclaringClass());
        System.out.println("green hashCode(): " + green.hashCode());
        System.out.println("green compareTo Color.GREEN: " + green.compareTo(Color.GREEN)); //比较
        System.out.println("green equals Color.GREEN: " + green.equals(Color.GREEN));
        System.out.format("green == Color.GREEN: %bn", green == Color.GREEN);
    }
}

构造函数

public enum ErrorCodeEn {
    OK(0, "成功"), //根据构造方法创建枚举常量“实例”
    ERROR_A(100, "错误A"),
    ERROR_B(200, "错误B");
    ErrorCodeEn(int number, String description) {
        this.number = number;
        this.description = description;
    }
    private int number;
    private String description;
    public int getNumber() {
        return number;
    }
    public String getDescription() {
        return description;
    }
    public static void main(String args[]) { // 静态方法
        for (ErrorCodeEn s : ErrorCodeEn.values()) {
            System.out.println("number: " + s.getNumber() + ", description: " + s.getDescription());
        }
    }
}
  • 不能使用 = 为枚举常量赋值,但可以用构造方法
  • 除了不能继承,基本上可以将 enum 看做一个常规的类

你可能感兴趣的