简体   繁体   中英

Why am I getting exception java.io.NotSerializableException?

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM