枚举ENUM的tostring() valueof()name()和values()用法

从jdk5出现了枚举类后,定义一些字典值可以使用枚举类型;

枚举常用的方法是values():对枚举中的常量值进行遍历;

valueof(String name) :根据名称获取枚举类中定义的常量值;要求字符串跟枚举的常量名必须一致;

获取枚举类中的常量的名称使用枚举对象.name()

枚举类中重写了toString()方法,返回的是枚举常量的名称;

其实toString()和value是相反的一对操作。valueOf是通过名称获取枚举常量对象。而toString()是通过枚举常量获取枚举常量的名称;

 

 1 package enumTest;
 2 
 3 /**
 4  * author:THINK
 5  * version: 2018/7/16.
 6  */
 7 public enum Color {
 8 
 9     RED(0,"红色"),
10     BLUE(1,"蓝色"),
11     GREEN(2,"绿色"),
12 
13     ;
14 
15 //    可以看出这在枚举类型里定义变量和方法和在普通类里面定义方法和变量没有什么区别。唯一要注意的只是变量和方法定义必须放在所有枚举值定义的后面,否则编译器会给出一个错误。
16     private int code;
17     private String desc;
18 
19     Color(int code, String desc) {
20         this.code = code;
21         this.desc = desc;
22     }
23 
24     /**
25      * 自己定义一个静态方法,通过code返回枚举常量对象
26      * @param code
27      * @return
28      */
29     public static Color getValue(int code){
30 
31         for (Color  color: values()) {
32             if(color.getCode() == code){
33                 return  color;
34             }
35         }
36         return null;
37 
38     }
39 
40 
41     public int getCode() {
42         return code;
43     }
44 
45     public void setCode(int code) {
46         this.code = code;
47     }
48 
49     public String getDesc() {
50         return desc;
51     }
52 
53     public void setDesc(String desc) {
54         this.desc = desc;
55     }
56 }

测试类

 1 package enumTest;
 2 
 3 /**
 4  * author:THINK
 5  * version: 2018/7/16.
 6  */
 7 public class EnumTest {
 8     public static void main(String[] args){
 9         /**
10          * 测试枚举的values()
11          *
12          */
13         String s = Color.getValue(0).getDesc();
14         System.out.println("获取的值为:"+ s);
15 
16 
17 
18         /**
19          * 测试枚举的valueof,里面的值可以是自己定义的枚举常量的名称
20          * 其中valueOf方法会把一个String类型的名称转变成枚举项,也就是在枚举项中查找字面值和该参数相等的枚举项。
21          */
22 
23         Color color =Color.valueOf("GREEN");
24         System.out.println(color.getDesc());
25 
26         /**
27          * 测试枚举的toString()方法
28          */
29 
30         Color s2 = Color.getValue(0) ;
31         System.out.println("获取的值为:"+ s2.toString());
32 
33     }

 

posted @ 2018-07-17 00:10  求知若渴&虚怀若愚  阅读(46445)  评论(0编辑  收藏  举报