一、什么叫枚舉?
在生活中,其實就是列舉的意思。在程序中,就是在一個類中列舉出,列舉出所有的常量,每一個常量都是一個實例。
二、枚舉有什么用?
通常用來限定取值范圍,所有內容只能從取值范圍中獲取,比如性別只有男和女,其他值都是不合法的。
三、舉例
實際開發場景中,枚舉類通常用來定義錯誤碼、交易碼等
public enum Color {
RED("紅色", 1), GREEN("綠色", 2), BLANK("白色", 3), YELLO("黃色", 4);
// 成員變量
private String name;
private int index;
// 構造方法
private Color(String name, int index) {
this.name = name;
this.index = index;
}
// 普通方法
public static String getName(int index) {
for (Color c : Color.values()) {
if (c.getIndex() == index) {
return c.name;
}
}
return null;
}
// get set 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
獲取枚舉值的方法:Color.RED.getName();
