0

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.

SnailK
  • 1
  • 3
  • I tried to change the type to ArrayList but it gives me 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')]. So no, the above solution did not work for me. – SnailK Feb 03 '23 at 07:22
  • 1
    see the accepted answer from the question linked in first comment - note: it is NOT using cast (a cast does NOT change the instance type); it is creating a new `ArrayList` – user16320675 Feb 03 '23 at 07:35
  • Thanks @user16320675! It worked. I misunderstood and tried casting hence was getting class java.util.ArrayList$SubList cannot be cast to class java.util.ArrayList . – SnailK Feb 03 '23 at 11:35

0 Answers0