Java枚舉總結(jié)
枚舉類型比較簡(jiǎn)單,下面兩個(gè)文章講的比較清楚:
附上實(shí)驗(yàn)代碼:
package com.minghui.test;
import java.util.EnumMap;
import java.util.EnumSet;
public enum Color implements Pritable {
RED("紅"), YELLOW("黃"), BLUE("藍(lán)");
public String mChineseName;
private Color(String chineseName) {
mChineseName = chineseName;
}
@Override
public String toString() {
return mChineseName;
}
@Override
public void print() {
System.out.println("index : " + ordinal() + " name :" + super.toString());
}
public static void main(String[] args) {
System.out.println("RED :" + RED + " YELLOW:" + YELLOW + " BLUE:" + BLUE);
RED.print();
YELLOW.print();
BLUE.print();
printColor(RED);
printColor(YELLOW);
printColor(BLUE);
EnumMap<Color, String> colorMap = new EnumMap<>(Color.class);
colorMap.put(RED, "FF0000");
colorMap.put(YELLOW, "0000FF");
colorMap.put(BLUE, "00FF00");
for (Color color : colorMap.keySet()) {
System.out.println("RGB Value of :" + color + " is " + colorMap.get(color));
}
EnumSet<Color> colorAllSet = EnumSet.allOf(Color.class);
System.out.println("colorAllSet set :" + colorAllSet);
EnumSet<Color> subColorSet = EnumSet.of(YELLOW, BLUE);
System.out.println("colorAllSet set :" + colorAllSet);
EnumSet<Color> emptyColorSet = EnumSet.noneOf(Color.class);
System.out.println("emptyColorSet set :" + emptyColorSet);
EnumSet<Color> oppColorSet = EnumSet.complementOf(subColorSet);
System.out.println("oppColorSet set :" + oppColorSet);
}
public static void printColor(Color color) {
String description;
switch (color) {
case BLUE:
description = "BLUE";
break;
case RED:
description = "RED";
break;
default:
description = "YELLOW";
}
System.out.println("Color is: " + description + " Chinese name is "
+ color.mChineseName);
}
}
public interface Pritable {
void print();
}