【问题标题】:How serialization work in LinkedList?LinkedList 中的序列化如何工作?
【发布时间】:2018-09-11 23:10:05
【问题描述】:
我不明白 LinkedList 如何理解反序列化后第一个和最后一个元素的位置。
因为字段有如下结构
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
谁能帮忙理解一下?
【问题讨论】:
标签:
java
serialization
linked-list
transient
【解决方案1】:
LinkedList method readObject 确定first 和last 在重建列表期间引用的内容。以下是链接中的代码:
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
linkLast 方法跟踪first 和last。它在要重构的第一个节点上初始化first 和last,并使用每个新重构的节点更新last。
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}