Hi, I use the enum make a few constants:
enum ids {OPEN, CLOSE};
the OPEN'valuse is zero, but I wanna it as 100. Is it possible?
Hi, I use the enum make a few constants:
enum ids {OPEN, CLOSE};
the OPEN'valuse is zero, but I wanna it as 100. Is it possible?
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
Java enums are not like C or C++ enums, which are really just labels for integers.
Java enums are implemented more like classes - and they can even have multiple attributes.
public enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.
See http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html for more.