1.定义常量:
public enum Color { RED,ORANGE,YELLOW,GREEN,INDIGO,BLUE,PURPLE}
2.用于switch:
enum Color { RED,ORANGE,YELLOW,GREEN,INDIGO,BLUE,PURPLE}public class Draw{ Color c = Color.BLUE; public void draw(){ switch(c){ case RED: c = Color.RED; break; case ORANGE: c = Color.ORANGE; break; case YELLOW: c = Color.YELLOW; break; case GREEN: c = Color.GREEN; break; case INDIGO: c = Color.INDIGO; break; case BLUE: c = Color.BLUE; break; case PURPLE: c = Color.PURPLE; break; } }}
3.在枚举中添加新方法:
public enum Color { RED(1,"红"), ORANGE(2,"橙"), YELLOW(3,"黄"), GREEN(4,"绿"), INDIGO(5,"靛"), BLUE(6,"蓝"), PURPLE(7,"紫"); //成员变量 private int sequence; private String name; //构造方法 private Color(int sequence, String name) { this.sequence = sequence; this.name = name; } //自定义方法 public static String getColorName(int sequence){ for (Color c : Color.values()) { if(c.getSequence() == sequence) return c.name; } return null; } //getter&setter public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
4.覆盖(重写)枚举的方法:
public enum Color { RED(1,"红"), ORANGE(2,"橙"), YELLOW(3,"黄"), GREEN(4,"绿"), INDIGO(5,"靛"), BLUE(6,"蓝"), PURPLE(7,"紫"); //成员变量 private int sequence; private String name; //构造方法 private Color(int sequence, String name) { this.sequence = sequence; this.name = name; } //覆盖方法 @Override public String toString() { return "顺序:"+this.sequence+"_颜色名:"+this.name; }}
5.实现接口:
interface Action{ void getDetail();}public enum Color implements Action{ RED(1,"红"), ORANGE(2,"橙"), YELLOW(3,"黄"), GREEN(4,"绿"), INDIGO(5,"靛"), BLUE(6,"蓝"), PURPLE(7,"紫"); //成员变量 private int sequence; private String name; //构造方法 private Color(int sequence, String name) { this.sequence = sequence; this.name = name; } @Override public void getDetail() { System.out.println("顺序:"+this.sequence+"_颜色名:"+this.name); }}
6.使用接口组织枚举:
public interface Food { enum Coffee implements Food{ BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO } enum Dessert implements Food{ FRUIT, CAKE, GELATO } }
7.枚举集合:
java.util.EnumSet和java.util.EnumMap是两个枚举集合。EnumSet保证集合中的元素不重复;EnumMap中的key是enum类型,而value则可以是任意类型。