枚举类

参考:https://juejin.cn/post/6844903737295634446

介绍

 

 

使用enum关键字定义枚举类,默认继承java.lang.Enum

另外,实现了Comparable接口

默认final,因此不能派生子类

枚举类的构造器只能用private访问控制符修饰,如果省略了构造器的访问控制符,则默认private修饰。

枚举类的所有实例必须在第一行显示列出系统自动添加public static finlal 修饰

枚举类提供抗了一个values()方法,该方法可以很方便的地遍历所有枚举值

This is the common base class of all Java language enumeration types. More information about enums, including descriptions of the implicitly declared methods synthesized by the compiler, can be found in section 8.9 of The Java™ Language Specification.

Note that when using an enumeration type as the type of a set or as the type of the keys in a map, specialized and efficient set and map implementations are available.

这是所有Java语言枚举类型的公共基类。关于枚举的更多信息,包括编译器合成的隐式声明方法的描述,可以在Java™语言规范的8.9节中找到。

注意,当使用枚举类型作为集合的类型或映射中的键的类型时,可以使用专门化和高效的集合和映射实现。

 

枚举类在编译后也是一个类类型

编译器生成两个方法 values()和valueOf(String name)

values()直接提供该枚举类型的数组

valueOf(String name) 指定枚举名称不存在会抛出IllegalArgumentException

//反编译Day.class
final class Day extends Enum
{
    //编译器为我们添加的静态的values()方法
    public static Day[] values()
    {
        return (Day[])$VALUES.clone();
    }
    //编译器为我们添加的静态的valueOf()方法,注意间接调用了Enum也类的valueOf方法
    public static Day valueOf(String s)
    {
        return (Day)Enum.valueOf(com/zejian/enumdemo/Day, s);
    }
    //私有构造函数
    private Day(String s, int i)
    {
        super(s, i);
    }
     //前面定义的7种枚举实例
    public static final Day MONDAY;
    public static final Day TUESDAY;
    public static final Day WEDNESDAY;
    public static final Day THURSDAY;
    public static final Day FRIDAY;
    public static final Day SATURDAY;
    public static final Day SUNDAY;
    private static final Day $VALUES[];

    static 
    {    
        //实例化枚举实例
        MONDAY = new Day("MONDAY", 0);
        TUESDAY = new Day("TUESDAY", 1);
        WEDNESDAY = new Day("WEDNESDAY", 2);
        THURSDAY = new Day("THURSDAY", 3);
        FRIDAY = new Day("FRIDAY", 4);
        SATURDAY = new Day("SATURDAY", 5);
        SUNDAY = new Day("SUNDAY", 6);
        $VALUES = (new Day[] {
            MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
        });
    }
}

作者:代码牛
链接:https://juejin.cn/post/6844903737295634446
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

枚举常见的方法

 

posted on 2023-03-16 17:42  or追梦者  阅读(5)  评论(0编辑  收藏  举报