序列化如何处理包含指针的数据结构,例如树和链表?
我之所以会产生这个疑问是,指针存储了节点的内存地址。在序列化和反序列化之后,不能保证它们会被加载到相同的内存位置。此外,如果将序列化数据通过网络发送到另一个系统,也会出现同样的问题。
那么它是如何工作的(如果它有效的话)?
序列化如何处理包含指针的数据结构,例如树和链表?
我之所以会产生这个疑问是,指针存储了节点的内存地址。在序列化和反序列化之后,不能保证它们会被加载到相同的内存位置。此外,如果将序列化数据通过网络发送到另一个系统,也会出现同样的问题。
那么它是如何工作的(如果它有效的话)?
Java doesn't have pointers. A variable in Java is a reference to a piece of data. Essentially, what this means is that you treat the variable just as you would treat the actual data, and Java takes care of the "pointer logic" for you (unlike, say, C, in which you must handle your own pointer logic).
When a class is serialized, all of the information contained in its references--that is, all of its member variables--must be serialized with it. You can think of this as recursively expanding each reference into a copy of the actual data referenced.
In a language that does include pointers (for instance, C), implementing serialization/deserialization methods that store and unpack pointers rather than the data each pointer references will indeed lead to you having arbitrary pointers in your deserialized data. (I.e., the serialization/deserialization will be incorrect.)
指针是引用。当序列化遇到引用时,它将递归地序列化它,这就是为什么所有成员也必须是可序列化的。它不会存储物理地址,而是构建自己的表,以便它可以跳过已经访问过的对象。在反序列化时,它将从该表构建新模型。
指针是对执行具有指针的程序的机器内存上特定位置的引用,它表示指针可能有一些数据。
当您序列化某些内容时,您应该序列化数据本身,而不是引用,这将毫无意义,因为如果您在另一端有数据,那么为什么要传输它呢?