疑问: clear()方法中对每个节点信息都进行清理操作,这样做的必要性是什么?
一.定义
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
继承自抽象类AbstractSequentialList,
实现Deque,表明该类实现了双端链表的功能
实现Cloneable,表明覆盖clone()方法以实现浅克隆
实现Serializable,表明改类可被序列化及反序列化
下面来看下抽象类AbstractSequentialList
/*
* 扩展自AbstactList
* AbstactList主要支持随机快速访问,
* AbstractSequentialList主要支持“连续访问”,底层为链表
* 类中的get,set,add,remove等方法都是通过listIterator来进行操作
* addAll时也通过迭代一条一条一条增加,效率与ArrayList的system.copyarraycopy相比应该有差距
*/
public abstract class AbstractSequentialList<E> extends AbstractList<E> {
protected AbstractSequentialList() {
}
public E get(int index) {
try {
return listIterator(index).next();
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public E set(int index, E element) {
try {
ListIterator<E> e = listIterator(index);
E oldVal = e.next();
e.set(element);
return oldVal;
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public void add(int index, E element) {
try {
listIterator(index).add(element);
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public E remove(int index) {
try {
ListIterator<E> e = listIterator(index);
E outCast = e.next();
e.remove();
return outCast;
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public boolean addAll(int index, Collection<? extends E> c) {
try {
boolean modified = false;
ListIterator<E> e1 = listIterator(index);
Iterator<? extends E> e2 = c.iterator();
while (e2.hasNext()) {
e1.add(e2.next());
modified = true;
}
return modified;
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public Iterator<E> iterator() {
return listIterator();
}
public abstract ListIterator<E> listIterator(int index);
}
接口Deque是对Queue的扩展。
Queue是一个基本的队列接口,提供了队列插入,删除,查看方法,但对每个方法都有两种形式,一种抛出异常(操作失败时),另一种返回一个特殊值(null 或 false,具体取决于操作)。如图:
Deque是一个基本的双端队列接口,提供了头部插入,尾部插入,头部删除等方法,同Queue一眼,每个方法都有两种形式。如图:
//不建议允许null值插入Deque的实现类,因为各种方法可能通过null为标识来判断Deque是否为空
public interface Deque<E> extends Queue<E> {
/**
* 删除从头开始,第一个匹配的元素
*/
boolean removeFirstOccurrence(Object o);
/**
* 删除从尾开始,第一个匹配的元素
*/
boolean removeLastOccurrence(Object o);
//返回一个逆向迭代器,默认修饰符修饰
Iterator<E> descendingIterator();
public int size();
boolean contains(Object o);
//其他方法略
}
二、底层实现
就是最基本的双向链表
三、变量及构造器
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
发现三个变量都拿transient 来修饰了,说明LinkedList应该也自定义了自己的序列化方法,翻到最后,果不其然。
private static final long serialVersionUID = 876323262645176354L;
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);
}
@SuppressWarnings("unchecked")
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());
}
四,基本逻辑方法
/**
*private, 只在本类中被调用
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
//size为0,first和last都为newNode
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
/**
* linkFirst private修饰,linkLast 默认修饰符,什么原因?
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
//size为0,first和last都为newNode
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
/**
* 默认修饰符
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
//succ为first,即第一个元素时,将newNode赋值于fitst
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
/**
* private 仅供此类使用
* 删除第一个元素f,且返回实际包含元素f.item
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
//赋值为null,供GC回收
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
//删除后,没有元素时,last赋值null
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* private 仅供此类使用
* 删除最后一个元素f,且返回实际包含元素f.item
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
//删除后,没有元素时,fitst赋值null
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* 默认修饰符
* 删除最元素f,且返回实际包含元素f.item
*/
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
//x为first元素时,first赋值next
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
//x为last元素时,last赋值ptev
last = prev;
} else {
next.prev = prev;
x.next = null;
}
//x既为last又为first时,我们发现在上述处理中fist=next=null,last=prev=null
x.item = null;
size--;
modCount++;
return element;
}
我们看到这些逻辑方法中有的是private修饰很好理解,而默认修饰符修饰的原因看到下面就会发现:原来迭代器类ListItr类中也有采用。
五、get,set,add,remove
这些方法基本都很好理解,再此处贴出几个模糊的地方
1.LinkedList实现了Deque接口,在上面Deque接口介绍中我们了解到,Deque对每个插入,查找,删除方法都有两种形式,一种抛出异常(操作失败时),另一种返回一个特殊值(null 或 false,具体取决于操作)。而我们看LinkedList的代码中的addFirst(),allLast(),offerFirst()等方法中得到了很好的体现。这种思想值得借鉴,一个抛异常,一个返回特殊值。
2.addAll方法,是把多个元素逐个添加,相比ArrayList的system.arrayCopyf,效率十分低下。
/**
* 添加元素的顺序于Collection迭代器顺序一致
* 批量添加多个元素时,linkedList效率及其低下
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
//转换为数组
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
//perd为空,即传入的index为0,要插入的元素赋值于fitst
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
//succ为空,即传入的index==size,
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
3.没有覆盖抽象类中的批量remove等方法。**LinkedList对批量操作数据的效率不高。**
六、clear()方法
/**
* 需要一步一步的清空每个Node,
* 把first,last的node信息清空,其他节点交给GC不可以吗?
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
需要将每个节点的数据都清空,为什么不只将first和last清空,这样其他节点没有对象引用,GC不是就自动回收?
关于这个问题,参考http://www.iteye.com/problems/71569,我是暂时没有理解,可能对JVM的了解太少,先留个坑吧。
七、clone及toArray
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
public Object clone() {
LinkedList<E> clone = superClone();
// 先清空数据
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// 将元素一个一个赋值
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
//与ArrayList 基本相同
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;
}
//与ArrayList 基本相同
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
八.迭代器
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
/**
* 通过使用ListItr来代理,这个想法好,
* 值提供了迭代器基本的三个方法hasNext(),next(),remove()
*/
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
总结:
1.Deque接口中对每个方法的都有两种形式的实现,一种形式在操作失败时抛出异常,另一种形式返回一个特殊值(null 或 false,具体取决于操作)。这种思想值得借鉴。
2.LinkedList 对批量操作效率低下
3.生成反向迭代器时,使用代理,很好的实现啊