How to use enum with grouping and subgrouping hierarchy/nesting

被刻印的时光 ゝ 提交于 2019-12-03 01:31:16

I would use a very simple enum constructor which associates the corresponding group with the enum value:

public enum Example {

    ENUM_A1 (Group.A),
    ENUM_A2 (Group.A),
    ENUM_A3 (Group.A),

    ENUM_B1 (Group.B),
    ENUM_B2 (Group.B),
    ENUM_B3 (Group.B),

    ENUM_C1 (Group.C),
    ENUM_C2 (Group.C),
    ENUM_C3 (Group.C);

    private Group group;

    Example(Group group) {
        this.group = group;
    }

    public boolean isInGroup(Group group) {
        return this.group == group;
    }

    public enum Group {
        A,
        B,
        C;
    }
}

Usage:

import static Example.*;
import Example.Group;
...

ENUM_A1.isInGroup(Group.A);  // true
ENUM_A1.isInGroup(Group.B);  // false

To do the subgroups you can do a similar kind of structure for Group as for Example, using Group(SubGroup ... subgroups) as a constructor and an EnumSet<SubGroup> to contain the subgroups.

Wendel

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<Example> groupA = EnumSet.of(ENUM_A1, ENUM_A2, ENUM_A3);
    public static EnumSet<Example> groupB = EnumSet.of(ENUM_B1, ENUM_B2, ENUM_B3);
    public static EnumSet<Example> 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");
    }
}

Small addition:

I do like both answers from @ELEVATE and @Wendel. And it depends (as always) on the scenario when to use which solution. If each entry must be part of a single group I prefer ELEVATE's solution, because it forces me to add this single group. However if only some enum need to be grouped or they are not distinct I go with Wendel's solution, because it is more flexible (but more error prone)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!