java枚举

发布时间 2023-09-26 16:09:54作者: 浮笙芸芸
package com.xn.enums;

public enum TestEnum {
    RED1("RED", 1),
    GREEN("GREEN", 2),
    BLACK("BLACK", 3);

    private String color;
    private int ori;

    // 构造方法
    private TestEnum(String color, int ori) {
        this.color = color;
        this.ori = ori;
    }

    @Override
    public String toString() {
        System.out.println("原来如此!!!");
        return this.color;
    }

    // 主方法
    public static void main(String[] args) {
        TestEnum[] values = TestEnum.values();
        for (TestEnum value : values) {
            System.out.println(value + " ori: " + value.ordinal());
        }

        System.out.println("======================");

        System.out.println(TestEnum.valueOf("RED1"));
        System.out.println("======================");
        System.out.println(RED1.compareTo(BLACK));
        System.out.println(BLACK.compareTo(GREEN));
    }
}

在Java中,枚举类型是通过使用enum关键字来定义的。枚举类型可以包含一个或多个枚举常量,每个常量都是枚举类型的实例。枚举常量是在枚举类型中预先定义的,它们是唯一的、已命名的对象。

如图我设置了两个属性color和ori,那么枚举的几个都会有这个属性,value.ordinal()就是这个枚举常量序号(从0开始),valueOf("枚举常量")就是根据枚举常量的名称获取对应的枚举常量,compareTo可以比较两个枚举常量的顺序,返回一个整数值,上面代码执行一下效果: