如何解决java.io.NotSerializableException: java.util.ArrayList$SubList异常
解决java.io.NotSerializableException: java.util.ArrayList$SubList异常
问题根源
List.subList()返回的ArrayList$SubList是原列表的视图类,它继承自AbstractList但未实现Serializable接口,序列化该子列表时会抛出异常。同时ArrayList$SubList并非ArrayList的子类,直接强转会触发类型转换错误。
正确解决方案
不要直接返回subList()的结果,而是将其包装为新的ArrayList实例——ArrayList实现了Serializable接口,且是独立于原列表的副本,完全规避视图类的序列化问题。
修正后的safeSubList方法
如果只需返回List类型:
public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) { int size = list.size(); if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { return new ArrayList<>(); // 返回空ArrayList,统一返回类型 } fromIndex = Math.max(0, fromIndex); toIndex = Math.min(size, toIndex); // 将subList视图包装为独立的ArrayList return new ArrayList<>(list.subList(fromIndex, toIndex)); }
如果需要明确返回ArrayList类型:
public static <T> ArrayList<T> safeSubList(List<T> list, int fromIndex, int toIndex) { int size = list.size(); if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { return new ArrayList<>(); } fromIndex = Math.max(0, fromIndex); toIndex = Math.min(size, toIndex); return new ArrayList<>(list.subList(fromIndex, toIndex)); }
之前尝试失败的原因
- 强转逻辑错误:
ArrayList$SubList是ArrayList的内部类,仅继承AbstractList,并非ArrayList的子类,因此(ArrayList<T>) list.subList(...)必然触发类型转换异常。 - 空列表类型不匹配:
Collections.emptyList()返回的是不可变空List实例,并非ArrayList,强转同样会报错,改用new ArrayList<>()可统一返回类型。
调用代码无需修改
原调用逻辑直接使用修正后的方法即可:
List<String> subList = ContextUtil.safeSubList(customerIds, i, i+10); List<Customer> customers = convertObjectsToCustomers(asiakashallinta.haeAsiakaslistaAsiakastunnuksila(getCustomerListQuery(subList, jopoContext), jopoContext)); if(customers != null){ result.addAll(customers); }
内容的提问来源于stack exchange,提问作者SnailK
相关产品推荐
相关产品推荐

