2 Replies Latest reply: Dec 4, 2009 9:01 AM by 843793 RSS

    Using ENUM with FLAGS in java

      HI all.

      in C# and C++ it is possilbe to declare a enum like this

      public enum MyEnum
      Default = 0,
      Val1 = 1,
      Val2 = 2,
      Val4 = 4,
      Val8 = 8,
      Val2OrVal4 = Val2 | Val4

      They call it enum wiht flag attribute.
      i want to do something like this in java, it this possible in java, or is it possible to have bitwise enum values in

        • 1. Re: Using ENUM with FLAGS in java
          If you come from C#/.NET then an important difference to notice is that in C# an enum is a special form of a integer constant (as it was in C and C++), while in Java an enum is its own class and the possible values are fully-fledged objects.

          So there is no direct numeric value in Java.

          If you want to represent some combination of enum values in Java, you can use an EnumSet:
          EnumSet<MyEnum> value2OrValue4 = EnumSet.of(MyEnum.Val2, MyEnum.Val4);
          • 2. Re: Using ENUM with FLAGS in java
            This is completely the wrong forum for this question.

            That said, don't forget that since java enums are fully fledged classes you can use the full range of class like constructs such as fields, methods and constructors.

            Thus, you could achieve what you are trying to do as follows (not that it is necessarily recommended):
            public class Main {
                enum E {
                    fa(0), fb(1), fc(2), fac(fa, fc);
                    private int m;
                    E(int bit) { m = (1 << bit); }
                    E(E... es) {
                        m = 0;
                        for (E e: es) { m |= e.getMask(); }
                    int getMask() { return m; }
                public static void main(String[] args) {
                    for (E e: E.values()) {
                        System.out.format("%s, mask = 0x%x%n", e.toString(), e.getMask());
            Running this produces the following output:
            fa, mask = 0x1
            fb, mask = 0x2
            fc, mask = 0x4
            fac, mask = 0x5
            Hope this helps, but don't post more on this here.