Relationship between transient keyword and serialization

< H3 id = "1transient modify instance variable" > 1 Transient modifier instance variable

Note: during serialization, even if the value of the instance variable is not saved, the field still exists, but the field points to a null pointer

< H3 id = "2static variable" > 2 Static variable

For business needs, it is not suitable to serialize some field values, such as bank password; More importantly, sometimes the default serialization method is not suitable, so the default serialization method is not used at this time, but the serialization form is defined by yourself. For example, the storage of elements in HashMap. The storage structure of HashMap element in Java 7 is the storage structure of Table + Chain (chain composed of nodes). The index of the corresponding element in table is calculated according to hash (key), and the element is inserted into the linked list at this index. Obviously, transient is used for table in the source code. Therefore, when serializing, table will not store values. Why is it so designed? Reason: instead of not serializing, the default serialization is not used. Because the element information in the table is the focus of our access, rather than the structure of the table, it is the key to reasonably access all the information in the table. Since the table structure is too complex (the linked list structure is a linked list composed of entry nodes), if the default serialization method is adopted, the complete structure of the table will be (including all linked lists) one image, which brings the following disadvantages: it takes a lot of time to traverse the table structure and takes up more storage space. By default, serialization recursively traverses the object graph. When the table is too large, stack overflow will occur, so avoid using the default serialization method.

import java. io.*;

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>