What's the Java equivalent of C#'s:
enum Foo
{
Bar = 0,
Baz = 1,
Fii = 10,
}
What's the Java equivalent of C#'s:
enum Foo
{
Bar = 0,
Baz = 1,
Fii = 10,
}
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.
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.
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.
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')