How to use enum with grouping and subgrouping hierarchy/nesting

前端 未结 3 1417
一向
一向 2021-02-04 00:32

I have one enum \'class\' called Example as follows:

enum Example {
//enums belonging to group A:
   enumA1,
   enumA2,
   enumA3,
//en         


        
3条回答
  •  野的像风
    2021-02-04 01:04

    You can use EnumSet to group various enums without creating a separate Enum class:

    public enum Example {
    
        ENUM_A1, ENUM_A2, ENUM_A3,
        ENUM_B1, ENUM_B2, ENUM_B3,
        ENUM_C1, ENUM_C2, ENUM_C3;
    
        public static EnumSet groupA = EnumSet.of(ENUM_A1, ENUM_A2, ENUM_A3);
        public static EnumSet groupB = EnumSet.of(ENUM_B1, ENUM_B2, ENUM_B3);
        public static EnumSet groupC = EnumSet.of(ENUM_C1, ENUM_C2, ENUM_C3);
    
    }   
    
    public static void main(String[] args){
        if(Example.groupA.contains(Example.ENUM_A1)){
           System.out.println("Group A contains ENUM A1");
        }
    }
    

提交回复
热议问题