枚舉類enum存儲於map、set


枚舉ENUM

用途:后端獲取 枚舉數據 統一打包給前端,前端通過下拉框展示數據。

例子中獲取枚舉值的方式有三種:

  1. OperTypeEnum.ADD
  2. OperTypeEnum.ADD.code  -> result: 1
  3. 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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM