在Java中序列化/反序列化自定义链表的正确方法

问题描述 投票:0回答:1

我正在向数据库项目添加序列化,但在理解如何反序列化链接列表时遇到问题。我认为我正确地序列化了它,但我希望获得有关我的实现的反馈,并且我不完全确定这是正确的方法。

我的自定义链表类报名:

/*
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
方法对于序列化是正确的,我将如何正确反序列化这个链表?我正在苦苦挣扎,需要一些建议。我读过的所有书都让我更加困惑。 Enrollment的所有成员都执行
Serializable
,所以我应该表现得很好。

编辑

这是我从下面的好建议中添加的反序列化方法,以防其他人想看到它以供将来参考:

    void loadEnrollment(String filename) throws ClassNotFoundException, IOException
    {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
        allEnrollment = (Enrollment)in.readObject();
        
    }
java serialization linked-list deserialization
1个回答
5
投票

您无需执行任何操作。只要

Enrollment
Student
类是
Serializable
,序列化列表头就会序列化整个列表,反序列化就会恢复整个列表。

void saveEnrollment(String filename) throws IOException
{
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
    out.writeObject(allEnrollment);
    out.close();
}
© www.soinside.com 2019 - 2024. All rights reserved.