我将序列化添加到我的数据库项目中,并且我在理解如何反序列化链接列表时遇到问题。我认为我正确地序列化了,但是我想在那里反馈我的实现以及我并不完全确定它是正确的方法。
我的自定义链接列表注册:
/*
class which is used to create the
enrollment linked list referencing
Student and Course objects
*/
public class Enrollment implements Serializable
{
private Student student;
private Course course;
private Enrollment link;
public Enrollment(Student student, Course course)
{
this.student = student;
this.course = course;
this.link = null;
}
//returns student object to caller
public Student getStudent()
{
return student;
}
//sets student field
public void setStudent(Student student)
{
this.student = student;
}
//returns course object to caller
public Course getCourse()
{
return course;
}
//sets course field
public void setCourse(Course course)
{
this.course = course;
}
//returns link to caller
public Enrollment getLink()
{
return link;
}
//sets link field
public void setLink(Enrollment link)
{
this.link = link;
}
}//end Enrollment
对于序列化,我有一个名为allEnrollment
的列表前面的对象引用。我认为仅序列化此引用不会序列化整个列表,而只是序列化第一个节点。这是我序列化链表的方法(如果不是这样的话,请纠正我):
void saveEnrollment(String filename) throws IOException
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
Enrollment currNode = allEnrollment;
//iterating thru linked list and writing each object to file
while (currNode != null)
{
out.writeObject(currNode);
currNode = currNode.getLink();
}
out.close();
}
假设我的saveEnrollment
方法对于序列化是正确的,我该如何正确地反序列化这个链表?我挣扎得很厉害,可以使用一些建议。我所做的所有阅读都让我更加困惑。所有入学成员都实施Serializable
,所以我应该在那里做得很好。提前谢谢。
编辑:
以下是我从下面的建议中添加的反序列化方法,以防其他人想要查看它以供将来参考:
void loadEnrollment(String filename) throws ClassNotFoundException, IOException
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
allEnrollment = (Enrollment)in.readObject();
}
答案 0 :(得分:5)
您无需做任何事情。只要Enrollment
和Student
类为Serializable
,序列化列表的头部将序列化整个列表,反序列化将恢复整个列表。
void saveEnrollment(String filename) throws IOException
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(allEnrollment);
out.close();
}