tags:

views:

383

answers:

2

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 &.

+2  A: 

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));
Eddie
I'm using retainAll... the test was wrong. Thanks anyway :)
dfa
What test was wrong?
Eddie
a unit test, not attached here
dfa
I think removeAll would be more obvious than emulating the bit-twiddling retainAll complementOf.
Tom Hawtin - tackline
@Tom Hawtin: True. I was emulating the previous logic, but you're right. removeAll would be more, well, logical in this position.
Eddie
A: 

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.

Paul Morie
no I don't want anymore use bit masks
dfa