1

LinkedList源码分析(五)

 1 year ago
source link: https://blog.51cto.com/u_13794952/5749333
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
LinkedList源码分析(五)_源码分析

🍁 作者:知识浅谈,CSDN博客专家,阿里云签约博主,InfoQ签约博主,华为云云享专家

📌 擅长领域:全栈工程师、爬虫、ACM算法

💒 公众号:知识浅谈

LinkedList源码分析(五)总结 🤞这次都给他拿下🤞

正菜来了⛳⛳⛳

🎈LinkedList源码中的函数

🍮private static class Node {}

含义:这个静态内部类Node表示的是表示的是List中节点,因为LinkedList是一个链表的形式,所以存储的是一个链表的结构,即每一个节点除了存储对应的元素值之外还要存储前置节点和后置接点的引用。

private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}

🍮Object clone()

含义:返回一个克隆的对象,但是这个拷贝是一个浅拷贝的,元素本身是没有被重新创建的,也就是Node中的item可能是一个引用,但是clone出来的两个对象中的item是不变的,从下边的clone.add(x.item);语句中可以看出clone的时候只是创建一个新的list,并且把现有的list中的元素添加到新创建的list中。

public Object clone() {
LinkedList<E> clone = superClone();

// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;

// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);

return clone;
}

🍮public Object[] toArray()

含义:toArray这个函数就是把列表中的所有元素方法一个数组中,并返回,相当于把链表数组化了。

public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}

🍮writeObject(java.io.ObjectOutputStream s)

含义:见名知意,这个函数的意思是把LinkedList中的每个元素序列化为数据流到s中去,从下边的函数中可以看出总共有两个类型,一个是写的LinkedList的size即LinkedList的元素数量,另一个是把所有元素写道流中。

private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();

// Write out size
s.writeInt(size);

// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}

🍮readObject(java.io.ObjectOutputStream s)

含义:这个函数的意思和上边的writeObject是相反的,上边的函数是序列化,下边的函数是反序列化,即把s流中的字节流反序列化为LinkedList中的元素。

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());
}

以上是是关于LinkedList源码分析的总结,希望有所帮助,下篇,开始读Collection中的set集合。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK