特别注意使用枚举与String做判断
Color.RED.equals("红色") 这个是枚举与字符串直接比较,结果:false
Color.RED.name.equals("红色") 这个是枚举属性值与字符串直接比较,结果:true
向枚举中添加新方法
1 public enum Color {
2 RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
3 // 成员变量
4 private final String name;
5 private final int index;
6 // 构造方法
7 private Color(String name, int index) {
8 this.name = name;
9 this.index = index;
10 }
11 // 普通方法
12 public static String getName(int index) {
13 for (Color c : Color.values()) {
14 if (c.getIndex() == index) {
15 return c.name;
16 }
17 }
18 return null;
19 }
20 // get set 方法
21 public String getName() {
22 return name;
23 }
24 public void setName(String name) {
25 this.name = name;
26 }
27 public int getIndex() {
28 return index;
29 }
30 public void setIndex(int index) {
31 this.index = index;
32 }
33 }
枚举类型对象之间的值比较,是可以使用==,直接来比较值,是否相等的,不是必须使用equals方法的哟。