如何确保枚举字段值是唯一的?

时间:2017-12-20 15:29:56

标签: java enums

假设您在枚举中有一个整数字段,并且您希望确保每个枚举常量都具有唯一的字段值。你会怎么做?

1 个答案:

答案 0 :(得分:0)

使用静态初始值设定项(受Unique enum member values启发):

enum MyEnum {
    CONST_1(5); //...
    private int code;
    public MyEnum(int code) {
        this.code = code;
    } 
    public int getCode() {
        return this.code;
    } // ...

    static {
        // check that the codes are unique.
        if (Arrays.stream(MyEnum.values()).map(MyEnum::getCode).distinct()
            .count() != MyEnum.values().length)
        throw new IllegalStateException("Codes aren't unique.");
    }
}