Java枚举的使用(你想不到的妙用)

一说到枚举,大部分人都觉得就是key、value这样的使用。刚开始我也是这样的理解,其实枚举可以这样用,我是来自山东小伙子,这个demo是我将山东各城市的车牌号用来记录,在学习代码的同时也补习一下地理知识。话不多说,直接上代码:

import lombok.Getter;

/**
 * @author oak
 * @date 2020/3/20 15:40
 */
public enum LicensePlateEnum {

    A(1,"鲁A","济南"),B(2,"鲁B","青岛"),C(3,"鲁C","淄博"),D(4,"鲁D","枣庄"),
    E(5,"鲁E","东营"),F(6,"鲁F","烟台"),G(7,"鲁G","潍坊"),H(8,"鲁H","德州"),
    J(9,"鲁J","泰安"),K(10,"鲁K","威海"),L(11,"鲁L","日照"),M(12,"鲁M","滨州"),
    N(13,"鲁N","德州"),P(14,"鲁P","聊城"),Q(15,"鲁Q","临沂"),R(16,"鲁R","菏泽"),
    U(17,"鲁U","青岛增补"),Y(18,"鲁Y","烟台增补");

    LicensePlateEnum(Integer code, String city, String cityName) {
        this.code = code;
        this.city = city;
        this.cityName = cityName;
    }

    @Getter
    private Integer code;
    @Getter
    private String city;
    @Getter
    private String cityName;
  public static LicensePlateEnum forEach(String licensePlate) {
LicensePlateEnum[] licensePlateEnums = LicensePlateEnum.values();
for (LicensePlateEnum value : licensePlateEnums) {
if(licensePlate.equals(value.getLicensePlate())) {
return value;
}
}
return null;
  }
}

相信大家一眼就能看得明白,除了key、value这种用法,也可以当作一张mysql表使用。每一个变量都是一个字段。这样可以将数据库中的一些常量写在枚举中,减少IO的次数。

posted @ 2020-03-20 20:31  哦克Oak  阅读(658)  评论(0编辑  收藏  举报