假设您在枚举中有一个整数字段,并且您希望确保每个枚举常量都具有唯一的字段值。你会怎么做?
答案 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.");
}
}