用枚举enum替代int常量
生活随笔
收集整理的這篇文章主要介紹了
用枚举enum替代int常量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
枚舉的好處:
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:
1:RED=3
2:BLUE=5
3:BLACK=8
4:YELLOW=13
5:GREEN=28
其中,
/*** 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的效率非常高。
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));} }?
轉載于:https://www.cnblogs.com/davidwang456/p/6138717.html
總結
以上是生活随笔為你收集整理的用枚举enum替代int常量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java内存模型深度解析:总结--转
- 下一篇: Living in the Matrix