枚舉是JDK1.5版本新增的特性:泛型、Foreach等如今被廣泛應(yīng)用的特性也是由JDK1.5時(shí)所新增的,在JDK1.6后switch語句支持枚舉類型伞租。
枚舉最簡單的寫法
public enum Colors {
RED, GREEN, BLUE
}
枚舉帶參數(shù)寫法
public enum ColorsEnum {
RED("red", "紅色"), GREEN("green", "綠色"), BLUE("blue", "藍(lán)色");
private final String key;
private final String color;
ColorsEnum(String key, String color) {
this.key = key;
this.color = color;
}
public String getKey() {
return key;
}
public String getColor() {
return color;
}
// 提供靜態(tài)方法獲取對應(yīng)的Enum
public static ColorsEnum getEnumKey(String key) {
if (key == null) {
return null;
}
for (ColorsEnum colorsEnum : ColorsEnum.values()) {
if (key.equals(colorsEnum.getKey())) {
return colorsEnum;
}
}
return null;
}
}
Android 中的枚舉
google官方建議
文中描述說使用枚舉內(nèi)存會是使用靜態(tài)常量的2倍以上楼眷,根據(jù)不同的枚舉計(jì)算,超過的不止2倍斤富;
1:枚舉類型的引用需要內(nèi)存空間膏潮;
2:枚舉引用指向的對象需要內(nèi)存空間;(就這兩條就達(dá)到了2倍的了)
3:枚舉數(shù)組需要內(nèi)存空間满力;