枚举的简单应用(二)

枚举类

 1 package com.yeepay.sxf.euma;
 2 /**
 3  *枚举定义变量时,最后一个枚举要加;号
 4  *枚举自定义变量
 5  *枚举自定义方法
 6  *枚举重写方法
 7  * @author sxf
 8  *
 9  */
10 public enum Color {
11     //枚举常量.在常量结束时,需要加上 ;号
12     RED("红色",1),
13     GREEN("绿色",2),
14     BLANK("白色",3),
15     YELLO("黄色",4);
16     
17         //成员变量
18         private String str;
19         private int index;
20 
21         //构造方法
22         private Color(String str,int index){
23             this.str=str;
24             this.index=index;
25         }
26         //使用枚举进行判断
27         public static boolean comper(Color color){
28             if(color==RED){
29                 return true;
30             }
31             return false;
32         }
33         
34         //数据某个值,获取枚举
35         public static Color getIndexToColor(int index){
36             for(Color color:Color.values()){
37                 if(color.index==index){
38                     return color;
39                 }
40             }
41             return null;
42         }
43         
44         //覆盖方法
45         @Override
46         public String toString() {
47             return this.index+"---"+this.str;
48         }
49         
50         //set get 方法
51         public String getStr() {
52             return str;
53         }
54 
55         public void setStr(String str) {
56             this.str = str;
57         }
58 
59         public int getIndex() {
60             return index;
61         }
62 
63         public void setIndex(int index) {
64             this.index = index;
65         }
66         
67     
68     
69     
70     
71 }
View Code

测试类

 1 package com.yeepay.sxf.euma;
 2 
 3 
 4 public class Test {
 5     public static void main(String[] args) {
 6         test2();
 7     }
 8     
 9     
10     public static void test2(){
11         //直接使用枚举
12         boolean flag=Color.comper(Color.RED);
13         System.out.println("直接使用枚举的==>"+flag);
14         
15         //获取某个枚举中的值
16         int index=Color.BLANK.getIndex();
17         String str=Color.BLANK.getStr();
18         System.out.println("获取枚举中的值==>"+index);
19         System.out.println("获取枚举中的值==>"+str);
20         
21         //打印枚举,覆盖方法
22         String aString=Color.RED.toString();
23         System.out.println("打印枚举中的值==>"+aString);
24         
25         //调用枚举中的方法
26         Color color=Color.getIndexToColor(4);
27         System.out.println("调用枚举中的方法==>"+color.getStr());
28         
29     
30         
31     }
32 }
View Code

打印结果

直接使用枚举的==>true
获取枚举中的值==>3
获取枚举中的值==>白色
打印枚举中的值==>1---红色
调用枚举中的方法==>黄色

原文地址:https://www.cnblogs.com/shangxiaofei/p/4705793.html