java中enum并没那么智能,是从0开始自增的。可以维护一个static变量实现任意自增:
import java.util.EnumSet;
public class EnumTest {
public static void main(String[] args) {
for (MSG_TYPE msg_type : EnumSet.allOf(MSG_TYPE.class))
{
System.out.println(msg_type.name() + " " +
msg_type.ordinal() + " " +
msg_type.getValue());
}
}
}
enum MSG_TYPE {
MSG_LOGIN(500),
MSG_LOGOUT,
MSG_REGISTER,
MSG_SEARCH,
MSG_ADD(600);
private int value;
private static int nextValue;
MSG_TYPE(){
this(Counter.nextValue);
}
MSG_TYPE(int value){
this.value = value;
Counter.nextValue = value + 1;
}
public int getValue()
{
return value;
}
private static class Counter
{
private static int nextValue = 0;
}
}
结果:
MSG_LOGIN 0 500
MSG_LOGOUT 1 501
MSG_REGISTER 2 502
MSG_SEARCH 3 503
MSG_ADD 4 600