代码之家  ›  专栏  ›  技术社区  ›  krltos

将ArrayList强制转换返回列表与未强制转换

  •  0
  • krltos  · 技术社区  · 7 年前

    @ModelAttribute(value = "attendanceStatuses")
    public List<Code> getAttendanceStatusCodes() {
        List<Code> attendanceStatuses= new ArrayList<Code>(
          cacheService.getValidCodesOfCodeGroup(CODE_GROUP));
        return attendanceStatuses;
    }
    

    @ModelAttribute(value = "attendanceStatuses")
    public List<Code> getAttendanceStatusCodes() {
        return cacheService.getValidCodesOfCodeGroup(CODE_GROUP);
    }
    

    cacheService方法是:

    List<Code> getValidCodesOfCodeGroup(CodeGroupName codeGroupName);
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Eran    7 年前

    第一个代码段返回 List 退回 cacheService.getValidCodesOfCodeGroup(CODE_GROUP) :

    new ArrayList<Code>(cacheService.getValidCodesOfCodeGroup(CODE_GROUP))
    

    第二个代码段没有,它只是返回 cacheService.GetValidCodeOfcodeGroup(代码组) .

    请注意,指定 列表 在返回局部变量之前对其进行修改没有任何区别。您可以将第一个代码段更改为:

    public List<Code> getAttendanceStatusCodes() {
        return new ArrayList<Code>(cacheService.getValidCodesOfCodeGroup(CODE_GROUP));
    }