带有LinkedList的Java序列化



我必须使一个链表Serializable。我了解基本知识,并成功地做到了,但这给我带来了一个曲线球。

该列表由节点组成,类是从接口派生的。每个节点的"数据"都是未定义的,这意味着任何数据类型或对象都可以保存在其中。在下面的代码段中,类型是"M"。如何指定其中可能包含的数据类型使其成为可序列化的?

我暂时正在用存储Strings和Doubles来测试它,但很快就会使用带有自定义类的对象make。我可以确认列表创建正确。

LinkedList类:

public class LinkedMovieList<M extends Comparable<M>>
implements GVLinkedList<M>, Serializable {
private class Node {
public M data;
public Node next;
Node(M element) {
data = element;
next = null;
}
}
Node head, tail;

序列化方法:

private GVLinkedList<Double> allVar, empty;
allVar = new DoublyLinkedMovieList<>();
empty = new DoubleLinkedMovieList<>();
private Double[] doubleList = {1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2};
for (Double v : doubleList){
allVar.insertLast(v);
}
File linkedFile = new File("LinkedMovieList.dat");
try{
FileOutputStream fileOut = new FileOutputStream(linkedFile);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(allVar);  //NotSerializableException thrown
objectOut.close();
FileInputStream fileIn = new FileInputStream(linkedFile);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
empty = (GVLinkedList<Double>) objectIn.readObject();
objectIn.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (ClassNotFoundException e){
e.printStackTrace();
}

任何帮助都将不胜感激!我觉得这很简单,我应该知道。。。堆栈跟踪:

java.io.NotSerializableException: edu.gvsu.cs163.LinkedMovieList$Node
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at edu.gvsu.cs163.Test.LinkedListTestDouble.isSerializable(LinkedListTestDouble.java:321)

Node类上实现Serializable接口

public class LinkedMovieList<M extends Comparable<M>>
implements GVLinkedList<M>, Serializable {
private class Node implements Serializable {
public M data;
public Node next;
Node(M element) {
data = element;
next = null;
}
}
Node head, tail;

相关内容

  • 没有找到相关文章

最新更新