3

I have an Enum in .Net. How can I rewrite this Enum in java?

Here is the Enum:

public enum AdCategoryType : short
{
    ForSale = 1,
    ForBuy = 2,
    ForRent = 8,
    WantingForRent = 16,
    WorkIsWanted = 32, 
    WorkIsGiven = 64
}
codekaizen
  • 26,990
  • 7
  • 84
  • 140
Troj
  • 11,781
  • 12
  • 40
  • 49
  • This is actually a flags-style enum and should probably have a "[Flags]" attribute. http://stackoverflow.com/questions/8447/enum-flags-attribute – RenniePet Aug 01 '13 at 13:43

3 Answers3

2

This gets you the enum:

public enum AdCategoryType {

    ForSale(1),

    ForBuy(2),

    ForRent(4),

    WantingForRent(8),

    WorkIsWanted(16),

    WorkIsGiven(32);

    private final int value;

    AdCategoryType(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • I get Java syntax errors when I do this, " expected" plus several more. Moving the "private final int value;" statement down, like in the other two answers, fixes this. Using Java 1.7 - maybe they've changed the syntax? – RenniePet Aug 01 '13 at 13:58
  • No, just didn't compile it three years ago when I first posted this. I added a type for value in the ctor and moved the declaration down. It works now. – duffymo Aug 01 '13 at 14:08
  • Wow, so you got your answer accepted and got two plus votes despite your answer not working! Never happens for me ... :-) – RenniePet Aug 01 '13 at 14:14
2

This will work:

public enum AdCategoryType {
    ForSale/*           */ (1 << 0), //
    ForBuy/*            */ (1 << 1), //
    ForRent/*           */ (1 << 2), //
    WantingForRent/*    */ (1 << 3), //
    WorkIsWanted/*      */ (1 << 4), //
    WorkIsGiven/*       */ (1 << 5);
    private final int value;

    private AdCategoryType(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
};

To get the value of ForBuy use AdCategoryType.ForBuy.getValue().

Margus
  • 19,694
  • 14
  • 55
  • 103
0
public enum Foo
{
   Bar(1),
   Baz(45);

   private short myValue;

   private short value()
   {
     return myValue;
   }

   public Foo(short val)
   {
      myValue = val;
   }

}

Burleigh Bear
  • 3,274
  • 22
  • 32