[英]Why am I getting exception java.io.NotSerializableException?
I am getting java.io.NotSerializableException: java.util.ArrayList$SubList for the following code. 我正在获取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]);
Obviously the class EntitiyMentionExample is Serializable that is why a Set<> of it is already stored in dat file (AllEMExampleObjects.dat). 显然,EntitiyMentionExample类是可序列化的,这就是为什么它的Set <>已存储在dat文件(AllEMExampleObjects.dat)中的原因。 Then why is it not Storing a single instance of it now?
那为什么现在不存储它的单个实例呢?
It's simply that ArrayList$SubList
doesn't implement Serializable
. 只是
ArrayList$SubList
不实现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
. AbstractList
和RandomAccess
都没有实现(或扩展) Serializable
,因此SubList
也没有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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.