dfa
dfa

Reputation: 116372

EnumSet 'and' operation

I'm porting some old code that uses the int enum pattern to Enum and EnumSet. It is very easy but I don't know how translate the following code to 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

~mask is simple as typing EnumSet.complementOf but I don't see how do &.

Upvotes: 3

Views: 3327

Answers (2)

Eddie
Eddie

Reputation: 54421

You want to use the Set method retainAll 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 previously had the following line in place of the simpler removeAll. Tom Hawtin pointed out that removeAll is simpler and achieves the same end. Originally, I just copied the OP's original logic as closely as possible, without trying to optimize.

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

Upvotes: 6

Paul Morie
Paul Morie

Reputation: 15788

CLASS_MODIFIERS, FIELD_MODIFIERS, and METHOD_MODIFIERS might be appropriate to leave as constants, since they are being used as bit masks. The link might help to clarify the point of this code.

Upvotes: -2

Related Questions