1、枚举的定义
可以根据实际需要在构造器中设置多个参数。
public enum Color {
RED("red", "红色"),
BULE("blue", "蓝色"),
YELLOW("yellow", "黄色");
private String type;
private String msg;
Color(String type,String msg) {
this.type = type;
this.msg = msg;
}
//省略get和set方法
}
2、枚举的使用
Color[] values = Color.values();
for (int i = 0; i < values.length; i++) {
System.out.println(values[i].getType() + "-----" + values[i].getMsg());
}
输出信息:
red-----红色
blue-----蓝色
yellow-----黄色
3、EnumSet和EnumMap
EnumSet<Color> enumSet = EnumSet.allOf(Color.class);
enumSet.add(Color.BULE);
enumSet.add(Color.RED);
enumSet.add(Color.YELLOW);
enumSet.add(Color.BULE);
for (Color color : enumSet) {
System.out.print(color.getType() + "\t");
}
EnumMap<Color, String> enumMap = new EnumMap<Color, String>(Color.class);
enumMap.put(Color.RED, "红色");
enumMap.put(Color.YELLOW, "黄色");
enumMap.put(Color.BULE, "蓝色");
System.out.println(enumMap);
输出信息:
red blue yellow
{RED=红色, BULE=蓝色, YELLOW=黄色}
可以看出EnumSet中存储的是唯一不重复的信息。
4、在switch-case语句中使用枚举
/**
* @Location com.giser
* @Notes {颜色}
* @author giserDev
* @Date 2019-05-11 12:06:35
*/
public enum Color {
RED(1, "red", "红色"),
BLACK(2, "black", "黑色"),
YELLOW(3, "yellow", "黄色"),
BLUE(4, "blue", "蓝色"),
WHITE(5, "white", "白色");
private Integer index;
private String value;
private String msg;
private Color(Integer index, String value, String msg) {
this.index = index;
this.value = value;
this.msg = msg;
}
/**
* @Notes {根据index获取对应颜色值,返回枚举类型}
* @author giserDev
* @Date 2019-05-11 12:08:34
*/
public static Color getValue(Integer index) {
Color[] colors = Color.values();
for (Color color : colors) {
if(color.index == index) {
return color;
}
}
return null;
}
//省略getters和setters
public static void main(String[] args) {
System.out.println(Color.getValue(3));
Random random = new Random();
int index = random.nextInt(Color.values().length) + 1;//[1,6)
while(true) {
System.out.println(index);
switch(Color.getValue(index)) {
case RED:
System.out.println(RED.msg);
break;
case BLACK:
System.out.println(BLACK.msg);
break;
case YELLOW:
System.out.println(YELLOW.msg);
break;
case BLUE:
System.out.println(BLUE.msg);
break;
case WHITE:
System.out.println(WHITE.msg);
break;
default:
break;
}
index = random.nextInt(5) + 1;
}
}
}