为什么 ArrayList 使用瞬态存储? [英] Why does ArrayList use transient storage?

查看:19
本文介绍了为什么 ArrayList 使用瞬态存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Java 的 ArrayList 的源代码,我遇到了它的支持数组声明:

I was reading the source of Java's ArrayList and I came across its backing array declaration:

private transient Object[] elementData;

为什么这需要是短暂的?为什么这个类不能序列化?

Why does this need to be transient? Why can't this class be serialized?

感谢您的帮助!

推荐答案

可以被序列化;ArrayList 类只是自己处理事情,而不是使用默认机制.查看该类中的 writeObject()readObject() 方法,它们是标准序列化机制的一部分.

It can be serialized; the ArrayList class just takes care of things itself, rather than using the default mechanism. Look at the writeObject() and readObject() methods in that class, which are part of the standard serialization mechanism.

如果您查看源代码,您会看到 writeObject() 不保存后备数组.相反,它一次一个地序列化元素(包括空值),直到 size() 限制.这避免了序列化数组的开销,尤其是数组末尾的任何未使用的插槽.在反序列化时,readObject() 会创建一个具有最小所需大小的新后备数组.

If you look at the source, you see that writeObject() does not save the backing array. Instead, it serializes the elements (including null values) one at a time up to the size() limit. This avoids the overheads of serializing the array, and especially any unused slots at the end of the array. On deserialization, a new backing array of the minimum required size is created by readObject().

这篇关于为什么 ArrayList 使用瞬态存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆