Unique enum member values

前端 未结 5 1089
星月不相逢
星月不相逢 2021-01-19 14:32

My problem: I want to specify a 1 to 1 connection between two enums. basically:

enum MyEnum{

    ENUM_VALUE_1,
    ENUM_VALUE_2,
    ENUM_VALUE_3,

}

enum          


        
5条回答
  •  旧巷少年郎
    2021-01-19 15:25

    How about this:

    public enum MyEnum {
    
        ENUM_VALUE_1,
        ENUM_VALUE_2,
        ENUM_VALUE_3,
    
    }
    
    // All enums taken.
    private static final Set taken = EnumSet.noneOf(MyEnum.class);
    
    enum MyOtherEnum {
    
        OTHER_ENUM_VALUE_1(MyEnum.ENUM_VALUE_3),
        OTHER_ENUM_VALUE_2(MyEnum.ENUM_VALUE_1),
        OTHER_ENUM_VALUE_3(MyEnum.ENUM_VALUE_2),
        OTHER_ENUM_VALUE_4(MyEnum.ENUM_VALUE_2);
    
        private MyEnum pair;
    
        MyOtherEnum(MyEnum pair) {
            if (taken.contains(pair)) {
                throw new IllegalArgumentException("Cannot pair the same MyEnum with two other enums! " + this);
            }
            taken.add(pair);
            this.pair = pair;
        }
    
    }
    
    public void test() {
        System.out.println("Hello: " + MyOtherEnum.OTHER_ENUM_VALUE_4);
    }
    

提交回复
热议问题