• java技术系列(一) Enum


    Enum的本质是类,继承自Enum类。

    enum直接使用==进行比较就可以。 

    类型的静态values方法,返回左右的枚举实例。

    ordinal方法返回enum声明中枚举常亮的位置。

    enum可以继承接口。api可以面向枚举的接口进行编程,这样这个接口可以接受任何接收实现该接口的枚举。

    适用场景:在实际编程中,存在稳定的有限数据集,如周一到周日,四季名称,男女性别等。适用于枚举。

    可以在switch中使用。

     1 package testjava;
     2 
     3 import com.alibaba.fastjson.JSON;
     4 
     5 /**
     6  * Create with test01
     7  * Auther: hp.wang on 2017/9/19
     8  * DateTime: 2017/9/19 20:16
     9  */
    10 public class testEnum {
    11 
    12     //常用定义Enum方法
    13     public enum Role {
    14         ADMIN(1), GUIDER(2), ROBOT(3),USER(4);  //顺序很重要
    15 
    16         private int value;
    17 
    18         Role(int v) {
    19             this.value = v;
    20         }
    21 
    22         public int getValue() {
    23             return value;
    24         }
    25 
    26         public static Role getByValue(int v) {
    27             for (Role r : Role.values()) {
    28                 if (r.getValue() == v) {
    29                     return r;
    30                 }
    31             }
    32             throw new IllegalArgumentException(v + " is not found in this enum.");
    33         }
    34     }
    35 
    36     public static void main(String[] args) {
    37         //使用方法:
    38         Role role = Role.ADMIN;
    39         System.out.println(role.toString() + ":" + role.getValue());
    40         System.out.println(Role.getByValue(2).toString());
    41         System.out.println("json:"+ JSON.toJSONString(role));
    42 
    43         Role role1=JSON.parseObject(""ADMIN"",Role.class);
    44         Role role2=JSON.parseObject(""USER"",Role.class);
    45 
    46         System.out.println("end");
    47     }
    48 }
  • 相关阅读:
    Django的FBV和CBV
    爬虫-----selenium模块自动爬取网页资源
    python摸爬滚打之day33----线程
    python摸爬滚打之day032 管道 数据共享 进程池
    python摸爬滚打之day030----进程
    爬虫重复请求超时
    指定页面刷新时间前端
    requests post请求,加上会话功能 以及url 编码问题
    爬虫常用mysql
    python操作excel以及word文档,pdf文档
  • 原文地址:https://www.cnblogs.com/netact/p/7554042.html
Copyright © 2020-2023  润新知