我有一个人为的问题。
假设我有一个用户链接列表,其中一个用户是“本周用户”:
public class UserOfTheWeek implements Serializable {
private UserNode root;
private UserNode userOfTheWeek;
//...
private class UserNode {
String username;
UserNode next;
}
public void saveToFile() {
ObjectOutputStream oos = new ...
oos.writeObject(root);
oos.writeObject(userOfTheWeek);
}
}
root
显然存储了对列表头部的引用,而 userOfTheWeek
可以指向任何节点。我想保存链接列表,但是保存 userOfTheWeek
会复制列表的一部分吗?如果列表开头的用户恰好是本周的用户,则这可能会将整个列表保存两次,更糟糕的是,userOfTheWeek
不会指向列表中由根
。
有谁知道会发生什么吗?如果没有,我也愿意接受替代解决方案。
最佳答案
I want to save the linked list, but will saving the userOfTheWeek make a copy of a part of the list?
没有。
If the user at the head of the list happens to be the user of the week, this could save the entire list twice
没有。
流知道哪些对象已被序列化到它,并且不会重新序列化它们。请参阅Object Serialization Specification #1.2 。同样,该对象仅被反序列化一次。对象图可以完全通用地序列化和恢复,包括循环。
and worse, userOfTheWeek wouldn't point to an object in the list pointed at by root.
您必须分别对其进行序列化和反序列化,但这不会导致创建新对象,它将引用列表中的对象。
关于java - 链表和指针插入列表的冗余序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37690341/