在JDK5中新引入的枚举完美地解决了之前通过常量来表示离散量所带来的问题,大大加强了程序的可读性、易用性和可维护性,并且在此基础之上又进行了扩展,使之可以像类一样去使用,更是为Java对离散量的表示上升了一个台阶。因此,如果在Java中需要表示诸如颜色、方式、类别、状态等等数目有限、形式离散、表达又极为明确的量,应当尽量舍弃常量表示的做法,而将枚举作为首要的选择。
public enum AppType {
All(0,""),Software(1,"soft"),Game(2,"game");
private int id;
private String name;
private AppType(int id,String name){
this.id = id;
this.name = name;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public static AppType valueOfName(String name){
for(AppType type:AppType.values()){
if(type.getName().equals(name))
return type;
}
throw new StoreDataException("Can not find corresponding type.");
}
public static AppType valueOf(int id){
for(AppType type:AppType.values()){
if(type.getId() == id)
return type;
}
throw new StoreDataException("Can not find corresponding type.");
}
}