I have one enum
'class' called Example
as follows:
enum Example {
//enums belonging to group A:
enumA1,
enumA2,
enumA3,
//enums belonging to group B:
enumB1,
enumB2,
enumB3,
//enums belonging to group C:
enumC1,
enumC2,
enumC3;
}
It's important for my project they all enums I work with belong to Example
(since this is an argument in a constructor of a class).
How do I use enum
hierarchy/nesting in order to achieve the following:
A method that tests whether an
enum
is of group A, B or C. For example, something likeExample.enumA1.isGroupBelonging(Group.A)
orisGroupBelonging(Example.enumA1,Group.A)
would be a public method that returns true.Be able to do the same thing with sub-groups of group
A
,B
andC
. For example, group A might have subgroupsa
,b
andc
. I then want a method that does something such asExample.enumA1.isSubGroupBelonging(SubGroup.a)
which is apublic boolean
.A way to do all this without needing to have some elaborate
enum
name that clogs up my code. For example, it would be nice to just be able to refer toExample.enumA1
throughout my other classes without needing to refer to it using something likeExample.enumA1(Group.A,SubGroup.a)
orExample.enumA1.Group.A.SubGroup.a
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)
You can use
EnumSet
to group various enums without creating a separateEnum
class:I would use a very simple enum constructor which associates the corresponding group with the enum value:
Usage:
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 anEnumSet<SubGroup>
to contain the subgroups.