Reputation: 955
I have kind of a contrived question.
Let's say I have a linked list of users, and one of these users is "User of the week":
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
obviously stores a reference to the head of the list, and userOfTheWeek
could point to any of the nodes. 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, and worse, userOfTheWeek
wouldn't point to an object in the list pointed at by root
.
Does anyone know what will happen? And if not, I am also open to an alternate solution.
Upvotes: 0
Views: 45
Reputation: 310876
I want to save the linked list, but will saving the userOfTheWeek make a copy of a part of the list?
No.
If the user at the head of the list happens to be the user of the week, this could save the entire list twice
No.
The stream knows which objects have already been serialized to it, and doesn't reserialize them. See the Object Serialization Specification #1.2. Similarly, the object is only deserialized once. Object graphs can be serialized and recovered in full generality, including cycles.
and worse, userOfTheWeek wouldn't point to an object in the list pointed at by root.
You would have to serialize and deserialize that separately, but it won't result in creation of a new object, it will refer to an object in the list.
Upvotes: 1