0

I am getting java.io.NotSerializableException: java.util.ArrayList$SubList for the following code.

        ObjectInputStream os=new ObjectInputStream(new FileInputStream("AllEMExampleObjects.dat"));
        Set<EntitiyMentionExample> AllEMs=(Set<EntitiyMentionExample>)(os.readObject());
        EntitiyMentionExample[] AllExamples=AllEMs.toArray(new EntitiyMentionExample[0]);

        ObjectOutputStream oo=new ObjectOutputStream(new FileOutputStream("C:\\Users\\15232114\\workspace\\Year2\\FormatedExamples\\TestSerialization.dat"));
        oo.writeObject(AllExamples[0]);

Obviously the class EntitiyMentionExample is Serializable that is why a Set<> of it is already stored in dat file (AllEMExampleObjects.dat). Then why is it not Storing a single instance of it now?

  • 1
    Show us the complete stacktrace. – Stephen C Oct 27 '16 at 12:53
  • Switch on the extended serialization debug info: http://stackoverflow.com/a/1660583/3788176. – Andy Turner Oct 27 '16 at 12:55
  • java.io.NotSerializableException: java.util.ArrayList$SubList at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at TrainingDataSetFormulator.main(TrainingDataSetFormulator.java:22) – chinmay choudhary Oct 27 '16 at 12:55
  • @Stephen C It is actually a much longer code. I put the Snip bit only? – chinmay choudhary Oct 27 '16 at 12:57

1 Answers1

6

It's simply that ArrayList$SubList doesn't implement Serializable.

Check the source code:

private class SubList extends AbstractList<E> implements RandomAccess {

Neither AbstractList nor RandomAccess implement (or extend) Serializable, so nor does SubList.

And this makes sense: to serialize a sublist - which is a view of a list, meaning updates to the sublist are reflected in the original list - you have to serialize the backing list too. But if you serialize and deserialize, changes to that instance will no longer be reflected as updates in the original backing list.

To serialize a sublist, you will need to copy it into its own (serializable) list first:

List<T> copyOfSubList = new ArrayList<>(subList);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243