日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

用枚举enum替代int常量

發布時間:2025/4/5 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用枚举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常量的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。