Java

如何在java中定义枚举类型

小樊
83
2024-09-12 04:25:43
栏目: 编程语言

在Java中,枚举(Enum)是一种特殊的类,用于表示固定数量的常量值

public enum Weekday {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY;
}

在这个例子中,我们定义了一个名为Weekday的枚举类型,它包含7个常量值,分别表示星期一到星期日。

要使用这个枚举类型,你可以直接引用它的常量值,如下所示:

public class EnumExample {
    public static void main(String[] args) {
        Weekday today = Weekday.MONDAY;
        System.out.println("Today is " + today);
    }
}

输出结果将会是:

Today is MONDAY

此外,枚举类型还提供了一些内置方法,如values()valueOf(),用于获取枚举类型的所有值或根据字符串名称查找特定值。例如:

public class EnumMethodsExample {
    public static void main(String[] args) {
        // 获取所有的Weekday值
        Weekday[] weekdays = Weekday.values();
        for (Weekday day : weekdays) {
            System.out.println(day);
        }

        // 根据字符串名称查找Weekday值
        Weekday dayByName = Weekday.valueOf("FRIDAY");
        System.out.println("Found by name: " + dayByName);
    }
}

输出结果将会是:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Found by name: FRIDAY

0
看了该问题的人还看了