java基础(三)之枚举用法
用法一:常量
public enum Color {
RED,GREEN,RED,YELLOW;
}
用法二:枚举中自定义方法
/**
* 枚举中自定义方法
*/
public enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLOW("黄色", 4);
//成员变量
public String name;
public int index;
//构造函数
private Color(String name, int index) {
this.name = name;
this.index = index;
}
//普通方法
public static String getName(int index) {
for (Color c : Color.values()) {
if (c.getIndex() == index) {
return c.name;
}
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
用法三:switch
public class TrafficLight {
Color signal = Color.RED;
public void change() {
switch (signal) {
case RED:
signal = Color.GREEN;
break;
case GREEN:
signal = Color.YELLOW;
break;
case YELLOW:
signal = Color.RED;
break;
}
}
}
用法四:枚举实现接口
枚举继承了java.lang.Enum.java不支持多继承,但枚举可以实现接口。
用法五:枚举集合
枚举集合有EnumMap与EnumSet两种,EnumMap集合中的key值是枚举,value可以是任何类型,numSet保证集合中的元素不重复。
实例用法:
public static void testEnumMap() {
EnumMap<Light, String> currLight = new EnumMap<Light, String>(Light.class);
currLight.put(Light.GREEN, "绿灯");
currLight.put(Light.RED, "红灯");
currLight.put(Light.YELLOW, "黄灯");
for (Light aLight : Light.values()) {
System.out.println("[key=" + aLight.name() + ",value="
+ currLight.get(aLight) + "]");
}
}