Precautions for using enumeration in switch statement

Article Introduction

In projects, we usually use enumerations to save the state values ​​of some objects.
For example, the four states of the project

  1. (0, development)
  2. (1, complete)
  3. (2, maintenance)
  4. (3, Pause)
    Now I have a requirement like this. I want to get all the projects that Person A participates in and classify them according to the status of the projects.
    I use the Map collection, with the state as the key, and the corresponding item list as the value, for storage.

Enumerate storage information

public enum AppStatusEnum {
    
    
    /**
     * 项目状态
     */
    //没有参与过项目的人
    ONGOING_APP(0, "开发中的项目"),
    //正在参与项目的人
    DONE_APP(1, "开发完成的项目"),
    //已参与过i项目
    PAUSED_APP(2, "暂停开发的项目"),
    MAINTAIN_APP(3,"维护中的项目");
    private final Integer status;
    private final String message;
    //项目模块的通用枚举
    AppStatusEnum(Integer status, String message) {
    
    
        this.status = status;
        this.message = message;

    }
    // 此方法是关键
    public static  AppStatusEnum getByStatus(Integer status) {
    
    
        for ( AppStatusEnum appStatus : values()) {
    
    
            if (appStatus.getStatus().equals(status)) {
    
    
                return appStatus;
            }
        }
        return null;
    }
}

Create storage collection

  Map<Integer,List<AppBaseDTO>> userBaseList = new HashMap<>();
        userBaseList.put(AppStatusEnum.ONGOING_APP.getStatus(),new ArrayList<>());
        userBaseList.put(AppStatusEnum.DONE_APP.getStatus(),new ArrayList<>());
        userBaseList.put(AppStatusEnum.PAUSED_APP.getStatus(),new ArrayList<>());
        userBaseList.put(AppStatusEnum.MAINTAIN_APP.getStatus(),new ArrayList<>());
        UserBaseDTO userBaseDTO = systemMapper.selectUserJoinAppByUserId(userId);

Add elements to the collection

Insert picture description here
An error occurred at this time: constant expression requires

Solution

switch(AppStatusEnum.getByStatus(app.getStatus())){
    
    
 case ONGOING_APP :
    userBaseList.get(AppStatusEnum.ONGOING_APP.getStatus()).add(app);
    break;
    case DONE_APP :
    userBaseList.get(AppStatusEnum.DONE_APP.getStatus()).add(app);
    break;
    case PAUSED_APP :
    userBaseList.get(AppStatusEnum.PAUSED_APP.getStatus()).add(app);
    break;
    case MAINTAIN_APP :
    userBaseList.get(AppStatusEnum.MAINTAIN_APP.getStatus()).add(app);
    break;
    default:
    throw  new BadRequestException("数据库或后端配置信息有误,请及时修改");
}

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/113917088