一.简单枚举
package helloworld;
public enum SimpleEnum {
SPRING,
SUMMER,
AUTUMN,
WINTER
}
-------------测试-----------------
public class enumMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(SimpleEnum sea:SimpleEnum.values())
{
System.out.println("季节:"+sea+" "+"ordinal:"+sea.ordinal());
}
}
}
调用枚举类的values()方法,遍历可以获得枚举类的所有枚举值
ordinal是排列的顺序,从0开始,每个枚举值都有一个对应的ordinal,按声明的顺序进行排序。
------------结果--------------------------
季节:SPRING ordinal:0
季节:SUMMER ordinal:1
季节:AUTUMN ordinal:2
季节:WINTER ordinal:3
二.带参数举
public enum season {
SPRING("春天","春风扶杨柳"),
SUMMER("夏天","映日荷花别样红"),
AUTUMN("秋天","落霞与孤鹜齐飞"),
WINTER("冬天","窗含西岭千秋雪");
private final String seasonName;
private final String seasonDesc;
private season(String seasonName,String seasonDesc)
{
this.seasonName=seasonName;
this.seasonDesc=seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
------------测试--------------------------------------
public class enumMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(season sea:season.values())
{
System.out.println("枚举类型:"+sea+" "+"季节:"+sea.getSeasonName()+" "+"季节描述:"+sea.getSeasonDesc()+" "+"ordinal:"+sea.ordinal());
}
}
}
--------------------测试结果-------------------------------
枚举类型:SPRING 季节:春天 季节描述:春风扶杨柳 ordinal:0
枚举类型:SUMMER 季节:夏天 季节描述:映日荷花别样红 ordinal:1
枚举类型:AUTUMN 季节:秋天 季节描述:落霞与孤鹜齐飞 ordinal:2
枚举类型:WINTER 季节:冬天 季节描述:窗含西岭千秋雪 ordinal:3
枚举类中的构造必须是private修饰的,所以枚举类被设计为单例模式,即枚举类型会在JVM加载时,实例化枚举对象,枚举类中有多少个就实例化多少个,JVM为了保证每一个枚举类型实例的唯一,是不会外部进行new操作的,所以把构造设为private,防止用户生成实例,破坏唯一性。