java之枚举类
枚举类:
使用自定义创建枚举类
public class TestEnum {
public static void main(String[] args) {
Season season1=Season.SPRING1;
System.out.println(season1);
System.out.println(season1.getSeasonName());
}
}
class Season{
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName,String seasonDesc) {
this.seasonDesc=seasonDesc;
this.seasonName=seasonName;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
}
public static final Season SPRING1=new Season("seasonName1", "seasonDesc1");
public static final Season SPRING2=new Season("seasonName2", "seasonDesc2");
public static final Season SPRING3=new Season("seasonName3", "seasonDesc3");
public static final Season SPRING4=new Season("seasonName4", "seasonDesc4");
}
使用enum创建枚举类
public class TestEnum {
public static void main(String[] args) {
Season season1=Season.SPRING1;
System.out.println(season1);
System.out.println(season1.getSeasonName());
System.out.println(Season.values());
for (int i = 0; i < Season.values().length; i++) {
System.out.println(Season.values()[i]);
}
String str="SPRING1";
Season sea=Season.valueOf(str);
System.out.println(sea);
}
}
enum Season{
SPRING1("seasonName1", "seasonDesc1"),
SPRING2("seasonName2", "seasonDesc2"),
SPRING3("seasonName3", "seasonDesc3"),
SPRING4("seasonName4", "seasonDesc4");
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName,String seasonDesc) {
this.seasonDesc=seasonDesc;
this.seasonName=seasonName;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
}
}