为什么我得到异常java.io.NotSerializableException?

chi*_*ary -1 java serialization

我得到java.io.NotSerializableException:java.util.ArrayList $ SubList以获取以下代码.

        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]);
Run Code Online (Sandbox Code Playgroud)

显然,EntitiyMentionExample类是Serializable,这就是它的Set <>已存储在dat文件(AllEMExampleObjects.dat)中的原因.那为什么现在不存储它的单个实例呢?

And*_*ner 5

它只是ArrayList$SubList没有实现Serializable.

检查源代码:

private class SubList extends AbstractList<E> implements RandomAccess {
Run Code Online (Sandbox Code Playgroud)

既没有AbstractList也没有RandomAccess实施(或延伸)Serializable,也没有SubList.

这是有道理的:序列化子列表 - 这是列表的视图,意味着子列表的更新反映在原始列表中 - 您还必须序列化后备列表.但是,如果序列化和反序列化,对该实例的更改将不再反映为原始支持列表中的更新.

要序列化子列表,您需要先将其复制到自己的(可序列化)列表中:

List<T> copyOfSubList = new ArrayList<>(subList);
Run Code Online (Sandbox Code Playgroud)