Java中List.get().addAll()不生效但set()正常的原因分析
问题原因与解决方案:getEmployeeList().addAll()不生效,setEmployeeList()正常的原因
核心问题分析
你的EmployeeSearchRespoonse类中手动重写的getEmployeeList()方法存在逻辑漏洞:
- 当成员变量
employeeList为null时,方法会新建一个ArrayList并返回,但没有将这个新列表赋值给类的成员变量employeeList。 - 调用
employeeSearchResponse.getEmployeeList().addAll(employeeListResponse)时,实际上是往这个临时创建的ArrayList里添加元素,而类本身的employeeList成员依然是null。后续输出或返回对象时,读取的是未被初始化的成员变量,所以看起来列表为空。 - 而
setEmployeeList(employeeListResponse)是直接将传入的列表赋值给类的成员变量employeeList,成员变量被正确赋值,所以返回时能正常显示列表内容。
另外,代码里还有两个明显的拼写错误需要修正:
- 类名
EmployeeSearchRespoonse多了一个字母o,应该是EmployeeSearchResponse - 成员变量
Emplyoee拼写错误,应该是Employee
修正方案
修改getEmployeeList()方法,在创建新列表后赋值给成员变量,确保后续操作作用在对象的成员变量上:
public List<Employee> getEmployeeList(){ if(employeeList == null){ employeeList = new ArrayList<>(); // 关键:将新创建的列表赋值给成员变量 } return employeeList; }
同理,getErrors()方法也存在相同问题(原代码中引用了未定义的errors变量,应该对应成员变量statusList),一并修正:
public List<Error> getErrors(){ if(statusList == null){ statusList = new ArrayList<>(); } return statusList; }
补充说明
你使用了Lombok的@Data注解,该注解会自动生成默认的getter方法,但你手动重写了getter,因此必须保证重写后的逻辑正确:既要返回非null的列表,也要确保成员变量被正确初始化,这样对列表的修改才能持久化到对象中。
内容的提问来源于stack exchange,提问作者developer2015
相关产品推荐
相关产品推荐

