Fue*_*son 2 java serialization linked-list deserialization
我正在向我的数据库项目添加序列化,并且在理解如何反序列化链接列表时遇到问题。我认为我已经正确地序列化了它,但是我想在那里获得有关我的实现的反馈,而且我不完全确定这是正确的方法。
我的自定义链接列表类注册:
/*
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
Run Code Online (Sandbox Code Playgroud)
对于序列化,我有一个称为的对象引用到列表的前面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();
}
Run Code Online (Sandbox Code Playgroud)
假设我的saveEnrollment方法对于序列化是正确的,我将如何正确地反序列化此链表?我很挣扎,可以使用一些建议。我所做的所有阅读使我更加困惑。所有的Enrollment成员都实施Serializable,所以我应该在那里。提前致谢。
编辑:
这是我从以下很棒的建议中添加的反序列化方法,以防万一其他人希望看到它以备将来参考:
void loadEnrollment(String filename) throws ClassNotFoundException, IOException
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
allEnrollment = (Enrollment)in.readObject();
}
Run Code Online (Sandbox Code Playgroud)
您不必做任何事情。只要Enrollment和Student类是Serializable,序列化列表的开头将序列化整个列表,反序列化将恢复整个列表。
void saveEnrollment(String filename) throws IOException
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(allEnrollment);
out.close();
}
Run Code Online (Sandbox Code Playgroud)