Often we see people do it this way,
public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3;This pattern has many problems, such as:
int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
SEASON_) to avoid collisions with other int enum types.
So why not use the enum type,
public enum UnitType {
MARINE, TANK
}
Java enum type are very different from C/C++. Java treats enumerations as a type separate from integers, and intermixing of enum and integer values is not allowed. In fact, an enum type in Java is actually a special compiler-generated class rather than an arithmetic type.
So if you want to have medic as 4, you have to put 2 undefined item in between.
public enum UnitType {
MARINE, TANK, UNDEFINED, UNDEFINED, MEDIC
That's why people don't often use the .ordinal() thing. Cuz it's too hard to handle, and Enumerated types are Comparable, using the internal integer; as a result, they can be sorted. So if you trying to write some functions that need the ordinal as input, and in the meanwhile your ordinal is changing. It's easy to see that your program will get messed up.
So we turn to use constructor and local variable and its getter, like this:
public enum UnitType {
MARINE(1), TANK(2);
private final int typeID;
UnitType(int number) {this.typeID = number;}
public int getTypeID() {return this.typeID;}
}
when we want to use its number, we can call UnitType.MARINE.getTypeID()
make use of valueOf
System.out.println("marine type id is " + UnitType.valueOf("MARINE").getTypeID());
Java 5.0 enumerations also can be used in switch statements, a nice convenience. Note that the enumeration values are still static class members, though not declared as such.
Reminders :
// play around with this code:)
import java.util.EnumSet;
public class main {
enum UnitType {
MARINE(1), TANK(2);
private final int typeID;
UnitType(int number) {this.typeID = number;}
public int getTypeID() {return this.typeID;}
}
enum OperatingSystems {
windows, unix, linux, macintosh;
public static final EnumSet<OperatingSystems> unixLike = EnumSet.range(unix, macintosh);
public final boolean supportCommandLine() {
return unixLike.contains(this);
}
public static final EnumSet<OperatingSystems> os = EnumSet.allOf(OperatingSystems.class);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World!");
System.out.println(UnitType.TANK +" type id is " + UnitType.valueOf("TANK").getTypeID());
for(OperatingSystems os: OperatingSystems.os) {
System.out.println(String.format("%d. %s Scholars " + (os.supportCommandLine()? "love it":"hate it") + ".",
os.ordinal() + 1, os));
}
}
}