简体   繁体   English

java序列化自定义链表

[英]java serialize a custom linked list

I didn't want to use the provided LinkedList Class so I made up a custom linked list.我不想使用提供的 LinkedList 类,所以我制作了一个自定义链表。 the problem is that i am worried of stack overflow problems that may occur when I serialize this object with the default read/write object fucntions问题是我担心使用默认读/写对象功能序列化此对象时可能会出现堆栈溢出问题

I saw from another SO post that you have to use custom serialization like below :我从另一篇 SO 帖子中看到,您必须使用如下自定义序列化:

MyClass{

    transient Node header; 

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        for (Entry e = header.next; e != header; e = e.next)
        out.writeObject(e.element);
    }
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
    }



}

this is the node class这是节点类

Node{
    transient Node next;
    transient Node prev;
    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        for (Entry e = header.next; e != header; e = e.next)
        out.writeObject(e.element);
    }
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
    }

}

How ever I am wondering, because I made the header field transient, when i read the class wouldn't it be null?我怎么想知道,因为我使头字段瞬态,当我阅读类时它不会为空吗? how do I make it refer to the header node...我如何使它引用头节点...

same for the nodes , since next and prev fields are transient when I read the object the fields would be null how do I make them maintain the references to each other节点相同,因为 next 和 prev 字段在我读取对象时是瞬态的,这些字段将为 null 我如何让它们保持对彼此的引用

Yes, you are right, they will be null.是的,你是对的,它们将为空。

You have to implement readObject in similar fashion you implemented write object:您必须以与实现 write 对象类似的方式实现 readObject:

while(elementsToRead()); // you need to know somehow how long you need to read
{
    add(inputStream.readObject());
}

I would suggest looking into implementations of read and write objects for lists in Java library.我建议研究 Java 库中列表的读写对象的实现。

Why you cannot use Java linked list?为什么不能使用Java链表? If something is missing, has you considered extending linkedLlist?如果缺少某些东西,您是否考虑过扩展linkedLlist?

You can basically look into Linked List source code and see how the serialization is performed.您基本上可以查看链接列表源代码并查看序列化是如何执行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM