EnumSet and operation

I am porting some old code that uses int enum pattern for Enum and EnumSet. It is very easy, but I do not know how to translate the following code into EnumSet ::

int mask = (kind == 'C' ? CLASS_MODIFIERS
            : kind == 'F' ? FIELD_MODIFIERS
            : kind == 'M' ? METHOD_MODIFIERS
            : (CLASS_MODIFIERS | FIELD_MODIFIERS | METHOD_MODIFIERS));
int bad_flags = flags & ~mask; // <--- this
flags &= mask; // <--- and this

~masksimple typing EnumSet.complementOfbut i don't see how & .

+3
source share
2 answers

You want to use the Set retainAll method to get the intersection of two sets:

public class Test {
  public enum Kind { CLASS, FIELD, METHOD }

  public void applyMask(char kind, EnumSet<Kind> flags) {
    final EnumSet<Kind> mask;
    switch (kind) {
      case 'C': mask = EnumSet.of(Kind.CLASS);    break;
      case 'F': mask = EnumSet.of(Kind.FIELD);    break;
      case 'M': mask = EnumSet.of(Kind.METHOD);   break;
      default:  mask = EnumSet.allOf(Kind.class); break;
    }
    EnumSet<Kind> badFlags = EnumSet.copyOf(flags);
    badFlags.removeAll(mask); // See note below
    flags.retainAll(mask);
  }
}

Note. I used to have the following line instead of a simpler one removeAll. Tom Hotin noted that it is removeAlleasier and achieves the same goal. Initially, I just copied the original OP logic as close as possible without trying to optimize.

    badFlags.retainAll(EnumSet.complementOf(mask));
+6

CLASS_MODIFIERS, FIELD_MODIFIERS METHOD_MODIFIERS , . .

-2

Source: https://habr.com/ru/post/1708953/


All Articles