resolve a java.util.ArrayList$SubList notSerializable Exception
Asked Answered
A

2

31

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);
Aceydeucy answered 25/10, 2014 at 23:11 Comment(4)
You can copy a list very easily. The ArrayList constructor will accept an existing collection (including your sublist) as an argument, and perform a copy.Vereen
@Vereen stole my answer. Just copy it to a list you know is serializable.Holdover
Ok, thnaks this is what I've done using an ArrayList!!Aceydeucy
@Vereen Why don't you post your comment as an answer? Then the OP can accept your answer.Giroux
I
67

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().

List<String> list = new ArrayList<String>(originalList.subList(0, 10));
Imray answered 26/10, 2014 at 16:35 Comment(0)
A
8

The solution was simply this code:

ArrayList<String> list = new ArrayList<String>();
list.addAll(originalList.subList(0, 10));
Aceydeucy answered 26/10, 2014 at 16:17 Comment(2)
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.Immortelle
If you care about performance you should not create twice the same sub-listBuffalo

© 2022 - 2024 — McMap. All rights reserved.