关于java:java-枚举类

37次阅读

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

参考文章

根底应用

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 看做一个惯例的类

正文完
 0