Unique enum member values

前端 未结 5 1086
星月不相逢
星月不相逢 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:30

    I put the "why" aside and try to answer your question:

    Create a static block in MyOtherEnum that performs the check:

    static{
        // This set stores all the used values
        EnumSet usedValues = EnumSet.noneOf(MyEnum.class);
    
        for(MyOtherEnum e : values()){
            // Value already present in the set?
            if(usedValues.contains(e.pair)) throw ...; // Duplicate 
            usedValues.add(e);
        }
    }
    

    But I have to agree with the comments: Instead of writing this check, you can also simply look at your code :).

提交回复
热议问题