枚举ENUM
用途:后端获取 枚举数据 统一打包给前端,前端通过下拉框展示数据。
例子中获取枚举值的方式有三种:
- OperTypeEnum.ADD
- OperTypeEnum.ADD.code -> result: 1
- OperTypeEnum.ADD.name -> result: "增加"
定义枚举
public enum OperTypeEnum {
ADD(1,"增加"),
DELETE(2,"删除"),
SELECT(3,"查询"),
UPDATE(4,"修改");
public int code;
public String name;
// 构造方法
OperTypeEnum(int code, String name){
this.code = code;
this.name = name;
}
// 自定义方法
public static Map<Integer,String> enumArrayToMap(){...}
}
一、EnumSet
// 创建枚举类的set集合
EnumSet enumSet = EnumSet.allOf(OperTypeEnum.class);
// 通过迭代器遍历
enumSet.iterator().forEachRemaining(ele -> System.out.println(ele));
//结果:[ADD, DELETE, SELECT, UPDATE]
二、EnumMap
EnumMap enumMap = new EnumMap(OperTypeEnum.class);
// 枚举数组
OperTypeEnum[] oArr = OperTypeEnum.values();
// foreach遍历数组
for(OperTypeEnum operTypeEnum : oArr){
// 插入数据
enumMap.put(operTypeEnum,operTypeEnum.name);
}
System.out.println(enumMap);
// 结果:{ADD=增加, DELETE=删除, SELECT=查询, UPDATE=修改}
三、自定义map
/**
* 遍历枚举,将数据存放于map中
* */
public static Map<Integer,String> enumArrayToMap(){
Map<Integer,String> map = new HashMap<>();
// values()获取枚举对象的数组:[OperTypeEnum,OperTypeEnum,...]
OperTypeEnum[] oArr = OperTypeEnum.values();
// for
// for (int i = 0; i < oArr.length; i++) {
// map.put(oArr[i].code,oArr[i].name);
// }
// forEach
for(OperTypeEnum operTypeEnum : oArr){
map.put(operTypeEnum.code,operTypeEnum.name);
}
return map;
}