0

In my c++ code i do stuff like this a lot

enum BarType {
    BT_UNKNOWN              = 0,
    BT_NORMAL               = 1,
    BT_BAR_REST             = 2,
    BT_REPEAT_PREV_MEASURES = 3,
    BT_TYPE_MASK            = 0x03,

    ... etc
};
BarType GetBarType(int bn)  { return (BarType)(m_barType[bn] & BT_TYPE_MASK); }

Is there a way to do this in java other than making everything ints which I hate because I like the type checking I get with enums?

Thanks

steveh
  • 1,352
  • 2
  • 27
  • 41

2 Answers2

3

The cleanest solution would be to use a java.util.EnumSet for each mask. You can then test whether a given enum value is in the set corresponding to a mask.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
  • thanks but that looks complex and slow and i do millions of these bit operations so i guess i'll have to stick with int – steveh Feb 15 '13 at 10:46
  • 1
    @steveh I don't think "looks complex and slow" is any substitute for measurement. As the documentation I linked to says: 'Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags.' – Patricia Shanahan Feb 15 '13 at 17:29
1

You can use the values array on the enum probably to achieve something like that.

 public enum BarType { BT_UNKNOWN, BT_NORMAL, BT_BAR_REST, BT_REPEAT }
 private static final int BT_TYPE_MASK = 0x03;

 public BarType getBarType(int bn) {
      return BarType.values()[bn & BT_TYPE_MASK]; 
 }

The order in values is the order in which the enum items are defined.

Stephan
  • 7,360
  • 37
  • 46