Java 枚举

枚举的定义、带字段与方法的枚举、遍历与 switch 配合。

Beginner
Key Points枚举是固定常量集合,本质是继承 Enum 的 final 类;可以带字段、构造方法和方法,比 int 常量更安全。

枚举的定义

An enum lists constants separated by commas. Each constant is a public static final instance; values() returns them all and valueOf() looks one up by name.

Java
enum Color {
    RED, GREEN, BLUE
}

public class EnumBasic {
    public static void main(String[] args) {
        Color c = Color.GREEN;

        System.out.println(c);
        System.out.println(c.ordinal());
        System.out.println(Color.valueOf("BLUE"));

        for (Color x : Color.values()) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}
Output
GREEN
1
BLUE
RED GREEN BLUE

带字段和方法的枚举

Enums may declare a constructor (implicitly private), fields and methods so each constant carries data — very handy for code-plus-label pairs.

Java
enum Status {
    OK(200, "success"),
    NOT_FOUND(404, "not found"),
    ERROR(500, "server error");

    private final int code;
    private final String label;

    Status(int code, String label) {
        this.code = code;
        this.label = label;
    }

    public int getCode() {
        return code;
    }

    public String getLabel() {
        return label;
    }

    public boolean isError() {
        return code >= 400;
    }
}

public class EnumFields {
    public static void main(String[] args) {
        System.out.println(Status.OK.getCode());
        System.out.println(Status.NOT_FOUND.getLabel());
        System.out.println(Status.ERROR.isError());
    }
}
Output
200
not found
true

枚举与 switch

switch accepts enums; write constant names in case without the class prefix. The Java 14 arrow form is terser and the compiler can flag missing branches.

Java
enum Level { LOW, MEDIUM, HIGH }

public class EnumSwitch {
    public static void main(String[] args) {
        Level lv = Level.MEDIUM;

        switch (lv) {
            case LOW -> System.out.println("low");
            case MEDIUM -> System.out.println("medium");
            case HIGH -> System.out.println("high");
        }

        int score = switch (lv) {
            case LOW -> 1;
            case MEDIUM -> 2;
            case HIGH -> 3;
        };
        System.out.println(score);
    }
}
Output
medium
2

Friends & Partners