构造器只能私有private,不允许public修饰,枚举类的方法和数据域可供外部访问。枚举enum只有一个值时,就成了单例。
1).ordinal()
返回枚举值在枚举类种的顺序。
WeekDay2.MON.ordinal(); //返回结果:1
WeekDay2.WEND.ordinal(); //返回结果:3
2).compareTo()
继承了Comparable接口,因此可以比较象与指定对象的顺序,返回的是两个枚举值序号之差.前提:两个枚举值必须属于同一个枚举类,否则会抛出ClassCastException()异常。
System.out.println(week1.compareTo(week2));//-2
3).values()
静态方法,返回一个包含全部枚举值的数组,是数组对象。
4).name()
返回枚举常量的名称,与toString()等效
5).valueOf()
name()是根据枚举对象获得该对象的名称字符串,而valueOf是根据指定的字符串,来获得对象
6).equals()
比较两个枚举类对象的引用。
/* 枚举过程 Strawberry2013/5/15 */ public class WeekDay { private WeekDay(){} //为私有 的,即不可new的 public static final WeekDay SUN = new WeekDay() {//匿名内部类, public WeekDay next() { return MON; } }; public static final WeekDay MON = new WeekDay(); public static final WeekDay TUES = new WeekDay(); public static final WeekDay WED = new WeekDay(); public static final WeekDay TRUR = new WeekDay(); public static final WeekDay FRI = new WeekDay(); public static final WeekDay SAT = new WeekDay(); public abstract WeekDay next(); //抽象的 }
public enum WeekDay2 { //可以将enum中的WeekDay2看着一个类名 SUN { public WeekDay next() { return MON; } }, MON,TUES,WEND,; //举内容为其具体实现对象(注意枚举内容的后面以分号标识) private WeekDay2(){}//私有化的构造函数,必须放在枚举的后面 public abstract WeekDay next(); }
/* 枚举常用实现过程方法 Strawberry2013/5/15 */ public class EnumTest { public static void main(String[] args) { System.out.println("haha"); WeekDay1 week1 = WeekDay1.MON; WeekDay1 week2 = WeekDay1.WEND; System.out.println(week1); System.out.println(week1.toString()); System.out.println(week1.name());//枚举对象的字符串 System.out.println(week1.ordinal());//顺序号 System.out.println(WeekDay1.valueOf("MON").ordinal());//返回一个字符串为MON的同名对象 System.out.println(WeekDay1.values().length); System.out.println(week1.compareTo(week2));//返回枚举两个枚举对象的orinal顺序值之差 //valueOf为枚举静态函数功能,根据 TrafficLamp t = TrafficLamp.RED; System.out.println(t.next()); System.out.println(t.getTime()); } public enum WeekDay1 { SUN, MON,TUES,WEND,; } } enum TrafficLamp { RED(30) { //构造函数以及匿名内部类 public TrafficLamp next(){ return GREEN; } }, YELLOW(40) { public TrafficLamp next(){ return RED; } }, GREEN(5) { public TrafficLamp next(){ return YELLOW; } }; public abstract TrafficLamp next(); private int time; private TrafficLamp(int time) { this.time = time; } public int getTime() { return time; } } /*enum的内部实现过程 */ public class WeekDay { private WeekDay(){} public static final WeekDay SUN = new WeekDay() { public WeekDay next() { return MON; } }; public static final WeekDay MON = new WeekDay(); public static final WeekDay TUES = new WeekDay(); public static final WeekDay WED = new WeekDay(); public static final WeekDay TRUR = new WeekDay(); public static final WeekDay FRI = new WeekDay(); public static final WeekDay SAT = new WeekDay(); public abstract WeekDay next(); } //等效于 public enum WeekDay2 { //可以将enum中的WeekDay2看着一个类名 SUN, MON,TUES,WEND,; //举内容为其具体实现对象(注意枚举内容的后面以分号标识) private WeekDay2(){}//私有化的构造函数,必须放在枚举的后面 }