java集合中LinkedList源码浅析

LinkedList就传说中的双向循环链表了。是List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。

链表操作优点:1.因为每个结点记录下个结点的引用,则在进行插入和删除操作时,只需要改变对应下标下结点的引用即可

              缺点:1.要得到某个下标的数据,不能通过下标直接得到,需要遍历整个链表。

但是在3,4W条数据下,JDK中的ArrayList何LinkedList在添加数据时的性能,其实几乎是没有差异的。

List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 getremoveinsert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列双端队列

此类实现 Deque 接口,为 addpoll 提供先进先出队列操作,以及其他堆栈和双端队列操作。

所有操作都是按照双重链接列表的需要执行的。在列表中编索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端)。

注意,此实现不是同步的。如果多个线程同时访问一个链接列表,而其中至少一个线程从结构上修改了该列表,则它必须 保持外部同步。(结构修改指添加或删除一个或多个元素的任何操作;仅设置元素的值不是结构修改。)这一般通过对自然封装该列表的对象进行同步操作来完成。如果不存在这样的对象,则应该使用 Collections.synchronizedList 方法来“包装”该列表。最好在创建时完成这一操作,以防止对列表进行意外的不同步访问,如下所示:

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

此类的 iteratorlistIterator 方法返回的迭代器是快速失败 的:在迭代器创建之后,如果从结构上对列表进行修改,除非通过迭代器自身的 removeadd 方法,其他任何时间任何方式的修改,迭代器都将抛出 ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,而不冒将来不确定的时间任意发生不确定行为的风险。

注意,迭代器的快速失败行为不能得到保证,一般来说,存在不同步的并发修改时,不可能作出任何硬性保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的方式是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。


LinkedList的声明

  1. public class LinkedList<E>  
  2.     extends AbstractSequentialList<E>  
  3.     implements List<E>, Deque<E>/*这是双端队列接口,这个接口扩展了Queue接口,提供了更多的方法,比如push,pop等*/, Cloneable, java.io.Serializable  
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>/*这是双端队列接口,这个接口扩展了Queue接口,提供了更多的方法,比如push,pop等*/, Cloneable, java.io.Serializable

所以LinkedList可以被用作Stack,Queue和Deque

 

来看一下链表结点的 定义

  1. private static class Entry<E> {  
  2.     E element;  
  3.     Entry<E> next;  
  4.     Entry<E> previous; //由此可以看出LinkedList是一个双向链表  
  5.    
  6.     Entry(E element, Entry<E> next, Entry<E> previous) {  
  7.         this.element = element;  
  8.         this.next = next;  
  9.         this.previous = previous;  
  10.     }  
private static class Entry<E> {
    E element;
    Entry<E> next;
    Entry<E> previous; //由此可以看出LinkedList是一个双向链表
 
    Entry(E element, Entry<E> next, Entry<E> previous) {
        this.element = element;
        this.next = next;
        this.previous = previous;
    }

LinkedList中声明了下面两个实例变量:

//头结点,起标记作用,并不记录元素

private transient Entry<E> header = new Entry<E>(null, null, null);

//链表的大小 ,即链表中元素的个数

    private transient int size = 0;

 

我们可以看到这两个 就是都被声明成了transient,所以在序列化的过程中会忽略它们,但是LinkedList提供的序列化方法writeObject(java.io.ObjectOutputStream s)中却序列化了size,并且将除header之外的所有结点都 写到序列化文件中了,那为什么要把size声明成transient呢,不解。。求解释。。

 

几个重要的方法:

  1. /** 
  2.      * Returns the indexed entry. 
  3.     根据给定的索引值离表头近还是离表尾近决定从头还是从尾开始遍历 
  4.      */  
  5.     private Entry<E> entry(int index) {  
  6.         if (index < 0 || index >= size)  
  7.             throw new IndexOutOfBoundsException("Index: "+index+  
  8.                                                 ", Size: "+size);  
  9.         Entry<E> e = header;  
  10.         if (index < (size >> 1)) { //如果较靠近有表头  
  11.             for (int i = 0; i <= index; i++)  
  12.                 e = e.next;  
  13.         } else { //较靠近表尾  
  14.             for (int i = size; i > index; i--)  
  15.                 e = e.previous;  
  16.         }  
  17.         return e;  
  18. }  
/**
     * Returns the indexed entry.
	根据给定的索引值离表头近还是离表尾近决定从头还是从尾开始遍历
     */
    private Entry<E> entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry<E> e = header;
        if (index < (size >> 1)) { //如果较靠近有表头
            for (int i = 0; i <= index; i++)
                e = e.next;
        } else { //较靠近表尾
            for (int i = size; i > index; i--)
                e = e.previous;
        }
        return e;
}

  1. /**  
  2. *将元素e添加到entry结点之前  
  3. */  
  4. private Entry<E> addBefore(E e, Entry<E> entry) {  
  5.     Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);  
  6.     newEntry.previous.next = newEntry; //将新结点与前后结点相连接   
  7.     newEntry.next.previous = newEntry;  
  8.     size++;  
  9.     modCount++;  
  10.     return newEntry;  
  11.     }  
  12.   
  13.   
  14. /** 
  15. *删除给定的结点e 
  16. */  
  17.     private E remove(Entry<E> e) {  
  18.     if (e == header)  
  19.         throw new NoSuchElementException();  
  20.   
  21.         E result = e.element;  
  22.     e.previous.next = e.next;  
  23.     e.next.previous = e.previous;  
  24.         e.next = e.previous = null;  
  25.         e.element = null;  
  26.     size--;  
  27.     modCount++;  
  28.         return result;  
  29.     }  
  30.   
  31.   
  32.   
  33. /**  
  34. *从表头开始遍历,返回此元素在表中的第一个位置 
  35.      */  
  36.     public int indexOf(Object o) {  
  37.         int index = 0;  
  38.         if (o==null) { //如果传入的元素是null,则不能调用 eqauls方法进行比较  
  39.             for (Entry e = header.next; e != header; e = e.next) {  
  40.                 if (e.element==null)  
  41.                     return index;  
  42.                 index++;  
  43.             }  
  44.         } else {  
  45.             for (Entry e = header.next; e != header; e = e.next) {  
  46.                 if (o.equals(e.element))  
  47.                     return index;  
  48.                 index++;  
  49.             }  
  50.         }  
  51.         return -1;  
  52.     }  
  53.   
  54. /** 
  55. *默认的添加动作,可以看到这个方法是把新元素添加 到表尾 
  56. */  
  57. public boolean add(E e) {  
  58.     addBefore(e, header); //加到头结点之前 ,即表尾  
  59.         return true;  
  60.     }  
  61.   
  62. /** 
  63. *默认的删除动作是删除链表的第一个元素,所以说在默认情况下,LinkedList其实扮*演的是一个队列的角色 
  64. */  
  65. public E remove() {  
  66.         return removeFirst();  
  67.     }  
  68.   
  69. /** 
  70. *返回第一个元素 
  71. */  
  72. public E peek() {  
  73.         if (size==0)  
  74.             return null;  
  75.         return getFirst();  
  76.     }  
/** 
*将元素e添加到entry结点之前 
*/
private Entry<E> addBefore(E e, Entry<E> entry) {
	Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
	newEntry.previous.next = newEntry; //将新结点与前后结点相连接 
	newEntry.next.previous = newEntry;
	size++;
	modCount++;
	return newEntry;
    }


/**
*删除给定的结点e
*/
    private E remove(Entry<E> e) {
	if (e == header)
	    throw new NoSuchElementException();

        E result = e.element;
	e.previous.next = e.next;
	e.next.previous = e.previous;
        e.next = e.previous = null;
        e.element = null;
	size--;
	modCount++;
        return result;
    }



/** 
*从表头开始遍历,返回此元素在表中的第一个位置
     */
    public int indexOf(Object o) {
        int index = 0;
        if (o==null) { //如果传入的元素是null,则不能调用 eqauls方法进行比较
            for (Entry e = header.next; e != header; e = e.next) {
                if (e.element==null)
                    return index;
                index++;
            }
        } else {
            for (Entry e = header.next; e != header; e = e.next) {
                if (o.equals(e.element))
                    return index;
                index++;
            }
        }
        return -1;
    }

/**
*默认的添加动作,可以看到这个方法是把新元素添加 到表尾
*/
public boolean add(E e) {
	addBefore(e, header); //加到头结点之前 ,即表尾
        return true;
    }

/**
*默认的删除动作是删除链表的第一个元素,所以说在默认情况下,LinkedList其实扮*演的是一个队列的角色
*/
public E remove() {
        return removeFirst();
    }

/**
*返回第一个元素
*/
public E peek() {
        if (size==0)
            return null;
        return getFirst();
    }

可以看出,如果表为空的时候 ,这个方法并不会抛出异常,而是返回null,而传统的(在Collections中声明的)方法则会抛出异常。相似的方法还有:poll,但请注意pop方法在表空的时候 会抛出异常。

 

还有一点请注意,如果先返回list的Iterator,之后 又对链表进行了添加删除修改操作,那么如果再使用返回的那个Iterator就会抛出ConcurrentModificationException。

 

 

最后看一下LinkedList是如何序列化和反序列化的,如果对这两个反序列化中用到的这两个回调方法有疑问的,可以看我的这篇博客 http://blog.csdn.net/moreevan/article/details/6697777

  1. /** 
  2.      * Save the state of this <tt>LinkedList</tt> instance to a stream (that 
  3.      * is, serialize it). 
  4.      * 
  5.      * @serialData The size of the list (the number of elements it 
  6.      *             contains) is emitted (int), followed by all of its 
  7.      *             elements (each an Object) in the proper order. 
  8.      */  
  9.     private void writeObject(java.io.ObjectOutputStream s)  
  10.         throws java.io.IOException {  
  11.     // Write out any hidden serialization magic  
  12.     s.defaultWriteObject();  
  13.   
  14.         // Write out size  
  15.         s.writeInt(size);  
  16.   
  17.     // Write out all elements in the proper order.  
  18.         for (Entry e = header.next; e != header; e = e.next)  
  19.             s.writeObject(e.element);  
  20.     }  
  21.   
  22.     /** 
  23.      * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is 
  24.      * deserialize it). 
  25.      */  
  26.     private void readObject(java.io.ObjectInputStream s)  
  27.         throws java.io.IOException, ClassNotFoundException {  
  28.     // Read in any hidden serialization magic  
  29.     s.defaultReadObject();  
  30.   
  31.         // Read in size  
  32.         int size = s.readInt();  
  33.   
  34.         // Initialize header  
  35.         header = new Entry<E>(nullnullnull);  
  36.         header.next = header.previous = header;  
  37.   
  38.     // Read in all elements in the proper order.  
  39.     for (int i=0; i<size; i++)  
  40.             addBefore((E)s.readObject(), header);  
  41.     }  
/**
     * Save the state of this <tt>LinkedList</tt> instance to a stream (that
     * is, serialize it).
     *
     * @serialData The size of the list (the number of elements it
     *             contains) is emitted (int), followed by all of its
     *             elements (each an Object) in the proper order.
     */
    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 (Entry e = header.next; e != header; e = e.next)
            s.writeObject(e.element);
    }

    /**
     * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is
     * deserialize it).
     */
    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();

        // Initialize header
        header = new Entry<E>(null, null, null);
        header.next = header.previous = header;

	// Read in all elements in the proper order.
	for (int i=0; i<size; i++)
            addBefore((E)s.readObject(), header);
    }

综上 ,我们可以看出。LinkedList是一个双向链表,它可以被当成栈,队列或双端队列来使用。它也提供 了随机访问元素的方法,不过这个访问的时间复杂度并不像ArrayList是O(1),而是O(n)。它删除给定位置的元素

的效率其实并不比ArrayList高。但它删除特定元素的效率 要比ArrayList高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值