Java之enumeration(枚举)
enumeration(枚举)是JDK1.5引入的新特性,放在java.lang包中。
1、枚举类方法介绍
package com.enums; public class TestEnum { public static void main(String[] args) { Season season = Season.autumn; System.out.println(season);//autumn System.out.println(season.compareTo(Season.autumn));//0 System.out.println(season.compareTo(Season.spring));//2 System.out.println(season.getDeclaringClass());//class com.enums.TestEnum$Season System.out.println(Season.autumn.name());//autumn System.out.println(Season.autumn.ordinal());//2 System.out.println(Season.autumn.toString());//autumn System.out.println(Season.valueOf(Season.class, "autumn"));//autumn } /** * int compareTo(E o) 比较此枚举与指定对象的顺序,返回值为枚举与指定对象的序号差。 * Class<E> getDeclaringClass() 返回与此枚举常量的枚举类型相对应的 Class 对象。 * String name() 返回此枚举常量的名称,在其枚举声明中对其进行声明。 * int ordinal() 返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零)。 * String toString() 返回枚举常量的名称,它包含在声明中。 * static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 返回带指定名称的指定枚举类型的枚举常量。 * * @author Administrator * */ public enum Season { spring, summer, autumn, winter; } }
2、遍历枚举
package com.enums; public class TestEnum1 { public static void main(String[] args) { for(Season s : Season.values()){ System.out.println(s); } } public enum Season { spring, summer, autumn, winter; } }
3、枚举值作为switch条件值
package com.enums; public class TestEnum2 { public static void main(String[] args) { Season season = Season.autumn; switch (season) { case spring: System.out.println("春天"); break; case summer: System.out.println("夏天"); break; case autumn: System.out.println("秋天"); break; case winter: System.out.println("冬天"); break; } } public enum Season { spring, summer, autumn, winter; } }
4、枚举中定义变量和方法
package com.enums; public class TestEnum3 { public static void main(String[] args) { System.out.println(Season.autumn.getName());//秋天 } public enum Season { spring("春天"), summer("夏天"), autumn("秋天"), winter("冬天"); private String name; private Season(String name){ this.name = name; } public String getName() { return name; } } }
详细原理请参考: