您的位置:首页 > 其它

一天一个类,一点也不累 之 LinkedList

2015-04-23 19:36 302 查看
我们的口号是,一天一个类,一点也不累 。。

今天要讲的是---LinkedList

首先,还是看看他的组织结构

Class LinkedList<E>

java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.AbstractSequentialList<E>
java.util.LinkedList<E>

Type Parameters:
E - the type of elements held in this collection

All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable


相比上两次介绍的两个类,他的实现接口多了一个Queue & Deque(一个是队列一个是双端队列)

既然这个也实现了List,同样具有List的一些性质,不知大家是否还记得List中的对象容许为NULL.

在API的官网上面明确说了一句:【[b]Note that this implementation is not synchronized.】 也就是说LinkedList也是非线程安全的。
[/b]

和ArrayList一样,库中存在线程安全的实现方法:

  List list = Collections.synchronizedList(new LinkedList(...));

所以在非线程安全的容器里面会有一个用来记录该对象改变次数的计数器modCount.


【首先声明一下,这个LinkedList里面维持这两个对象,一个是first,一个是last,他们的数据类型是Node的内部类。

  

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


1、构造方法:

[b]  LinkedList()
[/b]

    Constructs an empty list.
[b]  LinkedList(Collection<? extends E> c)
[/b]

    Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

2、首先特别解释一下,transient,这样的对象在行进序列话的时候, 是不被需序列化的,是临时的。
  因为在读源码的时候经常会出现这个关键字。

3、因为这个是链表,所以提供了一些关于链表的操作。
  e.g. getFirst() getLast()。。。。。。


4、值得注意的是从1.6开始,新增了一项称道的方法(虽然自己可以方便实现),这就是能够生成倒序的迭代器。

/**
* Adapter to provide descending iterators via ListItr.previous
*/
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();
}
}


这样以来就满足了在特定场合的需要。

哇喔,这个类要说的好少啊!~~~

不再说的多少,而在多思多练。

中国有句谚语:

        不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: