27

I am using SubList function on an object of type List. The problem is that I am using RMI and because the java.util.ArrayList$SubList is implemented by a non-serializable class I got the Exception described above when I try to pass the resulting object to a remote function taking as an argument a List as well. I've seen that I should copy the resulting List to a new LinkedList or ArrayList and pass that.

Does anyone know a function that helps as to easily do that for this for example ?

List<String> list = originalList.subList(0, 10);
zengr
  • 36,384
  • 37
  • 121
  • 187
Othmane
  • 926
  • 1
  • 14
  • 30

2 Answers2

53

It's because, List returned by subList() method is an instance of 'RandomAccessSubList' which is not serializable. Therefore you need to create a new ArrayList object from the list returned by the subList().

ArrayList<String> list = new ArrayList<String>(originalList.subList(0, 10));
aravindaM
  • 868
  • 8
  • 14
7

The solution was simply this code:

ArrayList<String> list = new ArrayList<String>();
list.addAll(originalList.subList(0, 10));
Othmane
  • 926
  • 1
  • 14
  • 30
  • 6
    The other proposed solution is better because it will pre-allocate the full size once, instead of possibly having to allocate the default size & then re-allocate space for the sublist while adding the elements. – Daniel Gray Nov 18 '16 at 13:31
  • If you care about performance you should not create twice the same sub-list – Jack Nov 16 '20 at 10:45