JAVA 列舉enum的使用
阿新 • • 發佈:2018-12-19
本文內容出自於《JAVA程式設計思想》,有興趣的讀者可自行翻閱
values() 的神祕之處
values() 是由編譯器新增的static方法,除此之外,還有valueOf()方法,與Enum類中的valueOf()方法不同的是引數的個數不同,如下是程式碼展示。
enum Explore{HERE,THERE} public class test01 { public static Set<String> analyze(Class<?> enumClass){ System.out.println("------Analyzing " + enumClass +"------"); System.out.println("Interfaces:"); for (Type t: enumClass.getGenericInterfaces()) { System.out.println(t+"---"); } System.out.println("Base: "+enumClass.getSuperclass()); System.out.println("Methods: "); Set<String> methods = new TreeSet<String>(); for (Method m:enumClass.getMethods() ) { methods.add(m.getName()); } System.out.println(methods); return methods; } public static void main(String[] args) { Set<String> exploreMethods = analyze(Explore.class); Set<String> enummMethods = analyze(Enum.class); System.out.println("Explore.containsAll(Enum)?"+ exploreMethods.containsAll(enummMethods)); System.out.println("Explore.containsAll(Enum)?"+ exploreMethods.removeAll(enummMethods)); System.out.println(exploreMethods); } } /** 輸出 ------Analyzing class Explore------ Interfaces: Base: class java.lang.Enum Methods: [compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, values, wait] ------Analyzing class java.lang.Enum------ Interfaces: java.lang.Comparable<E>--- interface java.io.Serializable--- Base: class java.lang.Object Methods: [compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, wait] Explore.containsAll(Enum)?true Explore.containsAll(Enum)?true [values] */
隨機選取的簡單示例
enum Activity{SITTING,LYING,STANDING,HOPPING,
RUNNING,DODGING,JUMPING,FALLING,FLYING}
public class RandomTest {
public static void main(String[] args) {
for (int i = 0;i<20;i++){
System.out.print(Enums.random(Activity.class)+" ");
}
}
}
介面組織的列舉
public enum SecurityCategory { STOCK(Security.Stock.class),BOND(Security.Bond.class); Security[] values; SecurityCategory(Class<? extends Security> kind){ values = kind.getEnumConstants(); } interface Security{ enum Stock implements Security{SHORT,LONG,MARGIN} enum Bond implements Security{MUNICIPAL,JUNK} } public Security randomSelection(){ return Enums.random(values); } public static void main(String[] args) { for(int i=0;i<10;i++){ SecurityCategory category = Enums.random(SecurityCategory.class); System.out.println(category+": "+category.randomSelection()+"|"); } } } /** output:BOND: MUNICIPAL|BOND: MUNICIPAL|STOCK: MARGIN|STOCK: MARGIN|BOND: JUNK|STOCK: SHORT|STOCK: LONG|STOCK: LONG|BOND: MUNICIPAL|BOND: JUNK| */
總結
列舉這一特性非常適合用來表示特定的有限屬性,除了上面所述之外,還有EnumSet,EnumMap,常量方法,需要使用的時候可再查閱資料