简体   繁体   中英

EnumSet with complex logic in Java

Let's say I have an enum:

enum EnumDemo{
 A1,
 A2,
 A3,

 B1,
 B2,
 B3,

 C1,
 C2,
 C3
}

What approach should I use to create enumset that can contain several EnumDemo elements,but all of the should be from one group, eg:

{A1, B2, C1}, {B1, C2}, but not {A1, A3, B1, C1}

Any thoughts are appreciated :)

You could use the EnumSet.of method to generate the sets, that would be the easiest and most readable:

 Set<EnumDemo> setA = EnumSet.of(EnumDemo.A1, EnumDemo.A2, EnumDemo.A3);
 Set<EnumDemo> setB = EnumSet.of(EnumDemo.B1, EnumDemo.B2, EnumDemo.B3);
 Set<EnumDemo> setB = EnumSet.of(EnumDemo.C1, EnumDemo.C2, EnumDemo.C3);

From there you can use Collections to generate the different sets you want using union or difference.

If you are looking to avoid having the problem that an A1 can be added into a set that already contains A2 you will have to handle this yourself using logic OR by creating three different Enum types ( EnumA , EnumB , EnumC ) which contain only their respective members.

You can keep in each enum element id of a group it belongs to. And create groups of enum based on this id:

enum EnumDemo{
 A1(0),
 A2(0),
 A3(0),

 B1(1),
 B2(1),
 B3(1),

 C1(2),
 C2(2),
 C3(2);

 private int groupId;

 private EnumDemo(int groupId) {
   this.groupId = groupId;
 }

 public static Set<EnumDemo> getGroup(int groupId) {
    Set<EnumDemo> group = EnumSet.noneOf(EnumDemo.class);
    for (EnumDemo value : values()) {
      if (value.groupId == groupId) {
        group.add(value);
      }
    }
    return group;
 }
}

This approach is good if groups are static and don't change over time. Also you can create enum like Group and use it instead of int for id. Also you can change groupId of elements dynamically in your app but I'm not sure it's good approach.

What about separating them to different enum types?

public interface EnumDemo {
}

enum AEnumDemo implements EnumDemo { A1, A2, A3 }
enum BEnumDemo implements EnumDemo { B1, B2, B3 }
enum CEnumDemo implements EnumDemo { C1, C2, C3 }

Then you can use EnumSet<? extends EnumDemo> EnumSet<? extends EnumDemo> as the type for your sets.

EnumSet<? extends EnumDemo> demos1 = EnumSet.allOf(AEnumDemo.class);
EnumSet<? extends EnumDemo> demos2 = EnumSet.allOf(BEnumDemo.class);
EnumSet<? extends EnumDemo> demos3 = EnumSet.of(AEnumDemo.A1, AEnumDemo.A3);
EnumSet<? extends EnumDemo> demos4 = EnumSet.of(BEnumDemo.B1, BEnumDemo.B2, BEnumDemo.B3);
EnumSet<? extends EnumDemo> demos5 = EnumSet.of(AEnumDemo.A1, BEnumDemo.B2);        // compile error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM