Java中如何创建一个枚举Enum类

从jdk5出现了枚举类后,定义一些字典值可以使用枚举类型。

枚举常用的方法是

values():对枚举中的常量值进行遍历;

valueof(String name) :根据名称获取枚举类中定义的常量值;要求字符串跟枚举的常量名必须一致;

获取枚举类中的常量的名称使用枚举对象.name()

枚举类中重写了toString()方法,返回的是枚举常量的名称;

其实toString()和value是相反的一对操作。valueOf是通过名称获取枚举常量对象。而toString()是通过枚举常量获取枚举常量的名称;

下面是枚举类的创建,和使用:

package enumTest;

public enum Color {

    RED(0,"红色"),
    BLUE(1,"蓝色"),
    GREEN(2,"绿色");

//    可以看出这在枚举类型里定义变量和方法和在普通类里面定义方法和变量没有什么区别。唯一要注意的只是变量和方法定义必须放在所有枚举值定义的后面,否则编译器会给出一个错误。
    private int code;
    private String desc;

    Color(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    /**
     * 自己定义一个静态方法,通过code返回枚举常量对象
     * @param code
     * @return
     */
    public static Color getValue(int code){

        for (Color  color: values()) {
            if(color.getCode() == code){
                return  color;
            }
        }
        return null;

    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

使用(测试类):

package enumTest;


public class EnumTest {
    public static void main(String[] args){
        /**
         * 测试枚举的values()
         *
         */
        String s = Color.getValue(0).getDesc();
        System.out.println("获取的值为:"+ s);


        /**
         * 测试枚举的valueof,里面的值可以是自己定义的枚举常量的名称
         * 其中valueOf方法会把一个String类型的名称转变成枚举项,也就是在枚举项中查找字面值和该参数相等的枚举项。
         */

        Color color =Color.valueOf("GREEN");
        System.out.println(color.getDesc());

        /**
         * 测试枚举的toString()方法
         */

        Color s2 = Color.getValue(0) ;
        System.out.println("获取的值为:"+ s2.toString());

    }

 参考:https://www.cnblogs.com/codething/p/9321174.html

发布了49 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/shenju2011/article/details/103476222