我正在阅读2008年由Joshua Bloch撰写的有效
Java,一个提示是用类替换枚举结构.这是从书中显示的例子.
public class Suit { private final String name; public Suit(String name) { this.name = name; } public String toString() { return name; } public static final Suit CLUBS = new Suit("clubs"); public static final Suit DIAMONDS = new Suit("diamonds"); public static final Suit HEARTS = new Suit("hearts"); public static final Suit SPADES = new Suit("spades"); }
我的问题是Java现在支持枚举类型,使用上面的方法还是个好主意吗?以下是Java枚举类型的示例.
public enum Day { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY }
解决方法
“有效的Java”书已经在将枚举引入语言之前写得很好,所以我建议使用枚举功能.幸运的是,Java枚举是非常多才多艺的,所以你可以使用枚举功能来密切关注Joshua的建议:
public enum Day { SUNDAY("Sunday",0),MONDAY("Monday",1),TUESDAY("Tuesday",2),WEDNESDAY("Wednesday",3),THURSDAY("Thursday",4),FRIDAY("Friday",5),SATURDAY("Saturday",6); private String name; private int ordinal; public String getName() { return name; } public int getOrdinal() { return ordinal; } public Day(String name,int ordinal) { this.name = name; this.ordinal = ordinal; } }