枚举

作者: 开心的小哈 | 来源:发表于2021-09-04 17:15 被阅读0次

    枚举的优势
    类型安全,紧凑有效的数据定义,可以和程序其他部分完美交互,运行效率高
    1.定义枚举类,使用enum 关键字

    package test.meiju;
    
    public enum Seasons2 {
        SPRING, SUMMER, AUTUMN, WINTER
    }
    
    

    2.定义完成后就可以使用啦

    package test.meiju;
    
    public class Demo {
        public static void doit(int i) {
            switch (i) {
            case Seasons.SPRING:
                System.out.println("春天");
                break;
            case Seasons.SUMMER:
                System.out.println("夏天");
                break;
            case Seasons.AUTUMN:
                System.out.println("秋天");
                break;
            case Seasons.WINTER:
                System.out.println("冬天");
                break;
            }
        }
    
        public static void doit2(Seasons2 s) {
    
            switch (s) {
            case SPRING:
                System.out.println("春天");
                break;
            case SUMMER:
                System.out.println("夏天");
                break;
            case AUTUMN:
                System.out.println("秋天");
                break;
            case WINTER:
                System.out.println("冬天");
                break;
            }
        }
    
        public static void main(String[] args) {
            doit2(Seasons2.WINTER);
            Seasons2 summer = Seasons2.SUMMER;
            Seasons2 valueOf = Seasons2.valueOf("SUMMER");
            int compareTo = valueOf.compareTo(summer);
            int ordinal = valueOf.ordinal();
            System.out.println("compareTo" + compareTo + "ordinal" + ordinal);
            System.out.println("" + valueOf);
            Seasons2[] values = Seasons2.values();
            for (Seasons2 seasons2 : values) {
                System.out.println(seasons2);
            }
            doit(3);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:枚举

          本文链接:https://www.haomeiwen.com/subject/zhirwltx.html