您的位置:首页 > 编程语言 > Java开发

Java枚举的使用

2014-11-05 17:03 330 查看
下面的类展示了枚举的用法

public class Client {
public static void main(String[] args) {
switch (Season.Time.Afternoon) {
case Afternoon:
System.out.println("good guy");
break;
case Dawn:
case Evening:
case Morning:
case Night:
System.out.println("I fool you");
break;
default:
System.out.println("what are you doing?");
break;
}
for(Boy boy:Boy.values()){
System.out.println(boy.toString()+"-"+boy.getAge()+"-"+boy.getHeight());
}
//EnumMap以enum值为key
EnumMap<Month, String> map = new EnumMap<Month, String>(Month.class);
map.put(Month.January, "一月");
map.put(Month.February, "二月");
map.put(Month.March, "三月");
map.put(Month.April, "四月");
map.put(Month.May, "五一");
map.put(Month.June, "六月");
map.put(Month.July, "七月");
for(Month m:map.keySet()){//Set,不重复
System.out.println(m);
}
for(String val:map.values()){//Collection
System.out.println(val);
}
for(Entry<Month, String> entry:map.entrySet()){//Set
System.out.println(entry.getKey()+"-"+entry.getValue());
}

}
public enum Month{
January,February,March,April,May,June,July
}
public enum Boy{//enum可以有自己的方法、属性
Zhangsan(16,1.55f),
Lisi(18,1.69f),
Wangwu(23,1.92f);//用分号来结尾
private final int age;
private final float height;
private Boy(int age,float height){//enum构造器只能是private,无法在外面创建对象
this.age = age;
this.height = height;
}
public int getAge(){
return age;
}
public float getHeight(){
return height;
}
}
private enum Season{//enum嵌套
Spring,Summer,Autumn,Winter;
public enum Time{
Dawn,Morning,Afternoon,Evening,Night
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  EnumMap enum