java中和枚举有关的关键字有很多,通常意义上用来定义有限个变量的关键字一般是指enum.
Enum
public enum DayOfWeek{
Monday, Tuesday;
}
上述代码定义了一个类DayOfWeek,并在该类中定义了两个DayOfWeek的对象。
很重要的一点是,任何enum的对象都是Enum类型的。如下:
public static void main(String[] args){
DayOfWeek day = DayOfWeek.Monday;
if(day instanceof DayOfWeek && day instanceof Enum){
System.out.println(day); //Monday
}
}
public enum DayOfWeek{
Monday, Tuesday;
}
如此,enum类的对象(实例)就都有了Enum的方法。
那么,事不宜迟,看看Enum的源码吧:
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {
//该属性保存枚举对象的名字
private final String name;
public final String name() {
return name;
}
//该属性保存枚举对象的顺序,从0开始
private final int ordinal;
public final int ordinal() {
return ordinal;
}
protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}
public String toString() {
return name;
}
Enum的源码很简单,除上述列出的方法和属性外,还有一个valueOf()方法,用于根据name返回对应的Enum。
对于Enum的综合用法如下:
public static void main(String[] args){
DayOfWeek day = DayOfWeek.Monday;
System.out.println(DayOfWeek.Tuesday.ordinal()+" "+
DayOfWeek.Tuesday.name()+" "+DayOfWeek.Tuesday.toString()); //1 Tuesday Tuesday
System.out.println(DayOfWeek.valueOf("Monday").compareTo(day)); //0
}
public enum DayOfWeek{
Monday, Tuesday;
}
属性和方法
在enum中可以定义属性和方法
public static void main(String[] args){
DayOfWeek.printSelf();
}
public enum DayOfWeek{
Monday("星期一",1), Tuesday("星期二",2);
private String desc;
private int val;
//enum的初始化方法只能定义为私有的,因为enum类的实例只能在enum内部初始化
private DayOfWeek(String desc, int val){
this.desc = desc;
this.val = val;
}
public static void printSelf(){
for(DayOfWeek day : DayOfWeek.values()){
System.out.println(day.name()+" "+day.desc+" "+day.val); //Monday 星期一 1 \n Tuesday 星期二 2
}
}
}