枚举的使用:
since 1.5
case1:定义常量
public enum Color {
RED, YELLOW, GREEN, BLUE;
}
说明:枚举的实例序列是用【逗号】隔开的;如果没有定义属性和方法,则实例序列最后的分号可以省略。
case2:switch语句
public enum Color {
RED, YELLOW, GREEN, BLUE;
}
public class EnumSwitch {
Color color = Color.RED;
public void testEnumSwitch() {
switch (color) {
case RED:
System.out.println("红色");
break;
case YELLOW:
System.out.println("黄色");
break;
case GREEN:
System.out.println("绿色");
break;
default:
System.out.println("蓝色");
break;
}
}
}
case3:在枚举中定义变量和方法(注:每个枚举实例都有这些变量和方法)
public enum Color {
RED("红色", 1), YELLOW("黄色"), GREEN, BLUE;
private String name;
private Integer index;
private Color() {
}
private Color(String name) {
this.name = name;
}
private Color(String name, Integer index) {
this.name = name;
this.index = index;
}
public static String getName(Integer index) {
for (Color c : Color.values()) { // 遍历枚举的所有实例;Color.values()可以简写成values()
System.out.println(c);
System.out.println(" ---> " + c.getName());
System.out.println(" ---> " + c.getIndex());
if (index == c.getIndex()) {
return c.name;
}
}
return null;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getIndex() { return index; }
public void setIndex(Integer index) { this.index = index; }
}
测试:
public class EnumMethod {
public static void main(String[] args) {
String name = Color.getName(2);
System.out.println("main获取Color的name:" + name);
}
}
结果:
RED
---> 红色
---> 1
YELLOW
---> 黄色
---> null
GREEN
---> null
---> null
BLUE
---> null
---> null
main获取Color的name:null
java.lang.Enum 枚举类型
最新推荐文章于 2021-03-13 12:09:07 发布