实例ENUM的tostring()valueof()name()和values()用途转载

原创
小哥 3年前 (2022-10-28) 阅读数 6 #大杂烩

从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     }
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除