enum

1. 定义在类内部的枚举类型

public class qq {

    public static void main(String[] args) throws ParseException {
        System.out.println(Color.BLACK.id);
        System.out.println(Color.BLACK.name);
        System.out.println(Color.BLACK.desc);
    }

    public enum Color {
        RED(1, "red", "红色"), BLACK(2, "black", "黑色"), BLUE(3, "blue", "蓝色");

        private int id;
        private String name;
        private String desc;

        private Color(int id, String name, String desc) {
            this.id = id;
            this.name = name;
            this.desc = desc;
        }
    }

}

# 上面代码的输出结果为:

2
black
黑色

# 需要注意的关键地方:

* 构造方法private

* 定义在类内部的枚举类型可以直接通过它的属性获取值

 2. 定义在类外部的枚举类型

public class qq {

    public static void main(String[] args) throws ParseException {
        System.out.println(Color.BLACK.getId());
        System.out.println(Color.BLACK.getName());
        System.out.println(Color.BLACK.getDesc());
    }

}

public enum Color {

    RED(1, "red", "红色"), BLACK(2, "black", "黑色"), BLUE(3, "blue", "蓝色");

    private int id;
    private String name;
    private String desc;

    private Color(int id, String name, String desc) {
        this.id = id;
        this.name = name;
        this.desc = desc;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

}

# 需要注意的关键地方:

* 通过get方法获取值

3. 遍历

public class qq {

    public static void main(String[] args) throws ParseException {
        for (Color color : Color.values()) {
            System.out.println(color.getId());
        }
        System.out.println(Color.existId(1));
    }

}

public enum Color {

    RED(1, "red", "红色"), BLACK(2, "black", "黑色"), BLUE(3, "blue", "蓝色");

    private int id;
    private String name;
    private String desc;

    private Color(int id, String name, String desc) {
        this.id = id;
        this.name = name;
        this.desc = desc;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

    public static boolean existId(int id) {
        for (Color color : values()) {
            if (color.getId() == id) {
                return true;
            }
        }
        return false;
    }
}

# 上面代码的输出结果为:

1
2
3
true

# 需要注意的地方:

enum 的内置方法 values()

posted on 2019-03-27 11:18  斜月三星一太阳  阅读(250)  评论(0编辑  收藏  举报