我必须制作一个可序列化的链表。我了解基本知识并成功完成了这项工作,但这使我感到很困惑。
该列表由Nodes组成,并且该类派生自接口。每个节点的“数据”都保持未定义状态,这意味着任何数据类型或对象都可以保留在其中。在下面的代码段中,类型为“ 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)
答案 0 :(得分:0)
在Serializable
类上实现Node
接口
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;