枚舉的好處:java
1. 類型安全性數組
2.使用方便性安全
public class EnumDemo { enum Color{ RED(3),BLUE(5),BLACK(8),YELLOW(13),GREEN(28); private int colorValue; private Color(int rv){ this.colorValue=rv; } private int getColorValue(){ return colorValue; } private int value(){ return ordinal()+1; } } public static void main(String[] args) { for(Color s : Color.values()) { //enum的values()返回一個數組,這裏就是Seasons[] System.out.println(s.value()+":"+s.name()+"="+s.getColorValue()); } } }
output:this
1:RED=3
2:BLUE=5
3:BLACK=8
4:YELLOW=13
5:GREEN=28spa
其中,code
/** * Returns the ordinal of this enumeration constant (its position * in its enum declaration, where the initial constant is assigned * an ordinal of zero). * * Most programmers will have no use for this method. It is * designed for use by sophisticated enum-based data structures, such * as {@link java.util.EnumSet} and {@link java.util.EnumMap}. * * @return the ordinal of this enumeration constant */ public final int ordinal() { return ordinal; }
EnumMap是專門爲枚舉類型量身定作的Map實現。雖然使用其它的Map實現(如HashMap)也能完成枚舉類型實例到值得映射,可是使用EnumMap會更加高效:它只能接收同一枚舉類型的實例做爲鍵值,而且因爲枚舉類型實例的數量相對固定而且有限,因此EnumMap使用數組來存放與枚舉類型對應的值。這使得EnumMap的效率很是高。blog
import java.util.*; public enum Phase { SOLID, LIQUID, GAS; public enum Transition { MELT(SOLID, LIQUID), FREEZE(LIQUID, SOLID), BOIL(LIQUID, GAS), CONDENSE( GAS, LIQUID), SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID); private final Phase src; private final Phase dst; Transition(Phase src, Phase dst) { this.src = src; this.dst = dst; } private static final Map<Phase, Map<Phase, Transition>> m = new EnumMap<Phase, Map<Phase, Transition>>( Phase.class); static { for (Phase p : Phase.values()) m.put(p, new EnumMap<Phase, Transition>(Phase.class)); for (Transition trans : Transition.values()) m.get(trans.src).put(trans.dst, trans); } public static Transition from(Phase src, Phase dst) { return m.get(src).get(dst); } } public static void main(String[] args) { for (Phase src : Phase.values()) for (Phase dst : Phase.values()) if (src != dst) System.out.printf("%s to %s : %s %n", src, dst, Transition.from(src, dst)); } }