Java枚举总结
枚举类型比较简单,下面两个文章讲的比较清楚:
附上实验代码:
package com.minghui.test;
import java.util.EnumMap;
import java.util.EnumSet;
public enum Color implements Pritable {
RED("红"), YELLOW("黄"), BLUE("蓝");
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();
}
网友评论