tags:

views:

1232

answers:

4

What's the Java equivalent of C#'s:

enum Foo
{
  Bar = 0,
  Baz = 1,
  Fii = 10,
}
+15  A: 

If you want attributes for your enum you need to define it like this:

public enum Foo {
    BAR (0),
    BAZ (1),
    FII (10);

    private final int index;   

    Foo(int index) {
        this.index = index;
    }

    public int index() { 
        return index; 
    }

}

You'd use it like this:

public static void main(String[] args) {
    for (Foo f : Foo.values()) {
       System.out.printf("%s has index %d%n", f, f.index());
    }
}

The thing to realise is that enum is just a shortcut for creating a class, so you can add whatever attributes and methods you want to the class.

If you don't want to define any methods on your enum you could change the scope of the member variables and make them public, but that's not what they do in the example on the Sun website.

Dave Webb
+1 for including the accessor :)Note that to get to the numerical value, you'd have to use Foo.BAR.index()
Matt
Note also, that if you want to get to the enum from the int code, you shoudl also add a static method that do the reverse mapping (with a switch or a map).
penpen
@penpen - a switch is a bummer to maintain; do the map, or just do a linear search, it's not that bad (except when it is)
Kevin Bourrillion
+2  A: 

Sounds like you want something like this:

public enum Foo {
    Bar(0),
    Baz(1),
    Fii(10);

    private int number;

    public Foo(int number) {
       this.number = number;
    }

    public int getNumber() {
        return number;
    }
}

For starters, Sun's Java Enum Tutorial would be a great place to learn more.

Peter Nix
A: 
public enum Foo {
    Bar(0),
    Baz(1),
    Fii(10);

    private final int someint;
    Foo(int someint) {
        this.someint = someint;
    }
}

In Java enums are very similar to other classes but the the Java compiler knows to treat a little differently in various situations. So if you want data in them like you seem to you need to have an instance variable for the data and an appropriate constructor.

Tendayi Mawushe
A: 

It is:

enum Foo
{
  Bar(0),
  Baz(1),
  Fii(10);

  private int index;

  private Foo(int index) {
   this.index = index;
  }
}

Note that to get the value of the enum from the index, Foo.valueOf(1) (*), would not work. You need do code it yourself:

public Foo getFooFromIndex(int index) {
 switch (index) {
 case 0:
  return Foo.Bar;
 case 1:
  return Foo.Baz;
 case 10:
  return Foo.Fii;

 default:
  throw new RuntimeException("Unknown index:" + index);
 }
}


(*): Enum.valueOf() return the enum from a String. As such, you can get the value Bar with Foo.valueOf('Bar')

Thierry-Dimitri Roy
Instead of that hand-coded method, lazily initialize a Map<Foo,Integer>.(for example using Maps.uniqueIndex() from Google Collections.)
Kevin Bourrillion