Reputation: 11
I am receiving error **caused java.io.NotSerializableException: java.util.ArrayList$SubList, please check method's implementation for the cause nested exception is:java.io.NotSerializableException: java.util.ArrayList$SubList ** with my below mentioned code...
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 Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return list.subList(fromIndex, toIndex);
}
The sublist not able to be serialized as it is of type List and sublist method of List is from RandomAccess and RandomAccess doesn't implement Serializable.
Attaching the code where and how this method is called:
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);
I tried to change the type to ArrayList, but then it gives class java.util.ArrayList$SubList cannot be cast to class java.util.ArrayList (java.util.ArrayList$SubList and java.util.ArrayList are in module java.base of loader 'bootstrap')]
Below is the code that I tried:
@SuppressWarnings("unchecked")
public static <T> ArrayList<T> safeSubList(ArrayList<T> list, int fromIndex, int toIndex) {
int size = list.size();
if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
return (ArrayList<T>)Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return (ArrayList<T>) list.subList(fromIndex, toIndex);
}
I am sure, this is not the correct way to fix it but wanted desperately to fix the issue. Any help would be appreciated.
Upvotes: 0
Views: 38