枚举类型是指由一组固定的常量组成合法的类型,由 enum 关键字来定义一个枚举类型。
定义
pulic enum Season{
SPRING(1),SUMMER(2),AUTUMN(3),WINTER(4)
}
用法
1)switch
import java.lang.Enum;
enum Season{
SPRING(1),SUMMER(2),AUTUMN(3),WINER(4);
private int code;
private Season (int code){
this.code = code;
}
public int getCode(){
return code;
}
}
public class EnumDome01 {
public String getChinesSeason(Season season){
StringBuffer allSeasion = new StringBuffer();
switch (season){
case SPRING:
allSeasion.append(season.name() + "SPRING对应的中国季节是春天,"+ "季节序号是" + season.getCode());
break;
case SUMMER:
allSeasion.append(season.name() + "SUMMER对应的中国季节是夏天,"+ "季节序号是" + season.getCode());
break;
case AUTUMN:
allSeasion.append(season.name() + "AUTUMN对应的中国季节是夏天,"+ "季节序号是" + season.getCode());
break;
case WINER:
allSeasion.append(season.name() + "WINER对应的中国季节是夏天,"+ "季节序号是" + season.getCode());
break;
default:
allSeasion.append("没有这个对应季节");
}
return allSeasion.toString();
}
public void doSamething(){
for (Season str:Season.values()){
System.out.println(getChinesSeason(str));
}
}
public static void main(String[] args){
EnumDome01 enum01 = new EnumDome01();
enum01.doSamething();
}
}
2)ordinal:返回枚举值在枚举类的顺序
Season.AUTUMN.ordinal(); //返回:2
Season.WINTER.ordinal(); //返回:3
3)compareTo():比较对象的顺序
int s = Season.AUTUMN.compareTo(Season.WINER);
4)values()返回一个包含枚举全部数值的数组
Season[] allvalue = Season.values();
5)toString():返回枚举常量的名称
6)equals():比较两个枚举类对象的引用
7)TreeSet():完成枚举排序操作
Set<Season> t = new TreeSet<Season>();
t.add(Season.SPRING);
t.add(Season.SUMMER);
t.add(Season.AUTUMN);
t.add(Season.WINTER);
Iterator it = t.iterator();
While(it.hasNaxt()){
Season s = it.next();
System.out.printl(s);
类集对枚举的支持
1)EnumMap
Map<Season,String> s = new EnumMap<Season,String>(Season.class);
2)EnumSet
EunmSet<Season> es = null;
es = EnumSet.allOf(Season.class); //将枚举的全部类型设置到EnumSet对象中