【问题标题】:returning the ArrayList cast to List vs no casting将 ArrayList 强制转换为 List 与没有强制转换
【发布时间】:2019-01-10 12:00:59
【问题描述】:

两者之间有什么区别(如果有的话):

@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);

【问题讨论】:

  • 关于问题的标题:这里不涉及强制转换。将现有的 List 传递给 ArrayList 的构造函数会创建该列表的副本,这与强制转换无关。

标签: java list arraylist casting


【解决方案1】:

第一个 sn-p 返回由cacheService.getValidCodesOfCodeGroup(CODE_GROUP) 返回的List 的副本:

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

第二个 sn-p 没有 - 它只是返回 cacheService.getValidCodesOfCodeGroup(CODE_GROUP)

不过,这些 sn-ps 中都没有强制转换。

请注意,在返回之前将 List 分配给局部变量没有区别。您可以将第一个 sn-p 更改为:

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

不改变行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2010-10-16
    • 2011-04-24
    • 2012-02-10
    • 2015-09-27
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多