列舉類的定義
阿新 • • 發佈:2018-12-27
1.十二生肖列舉類
public enum TwelveAnimalsEnum { //定義十二生肖對應的數字標示 DOG_FLAG(1,"狗"), CHICKEN_FLAG(2,"雞"), MONKEY_FLAG(3,"猴"), SHEEP_FLAG(4,"羊"), HORSE_FLAG(5,"馬"), SNAKE_FLAG(6,"蛇"), LOONG_FLAG(7,"龍"), RABBIT_FLAG(8,"兔"), TIGER_FLAG(9,"虎"), CATTLE_FLAG(10,"牛"), RAT_FLAG(11,"鼠"), PIG_FLAG(12,"豬"); private int key; private String desc; TwelveAnimalsEnum(int key, String desc) { this.key = key; this.desc = desc; } public int getKey() { return key; } public String getDesc() { return desc; } //可以根據key獲取對應生肖名稱 public static String getDescByKey(int key){ for (TwelveAnimalsEnum tEnum : TwelveAnimalsEnum.values()) { if (tEnum.getKey() == key) { return tEnum.getDesc(); } } return DOG_FLAG.getDesc(); } //根據生肖名稱獲取對應的key值 public static int getKeyByDesc(String desc){ for (TwelveAnimalsEnum tEnum : TwelveAnimalsEnum.values()) { if (tEnum.getDesc().equals(desc) ) { return tEnum.getKey(); } } return DOG_FLAG.getKey(); } }