`
BrokenDreams
  • 浏览: 249231 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
68ec41aa-0ce6-3f83-961b-5aa541d59e48
Java并发包源码解析
浏览量:98046
社区版块
存档分类
最新评论

Jdk1.6 Collections Framework源码解析(2)-LinkedList

阅读更多
        ArrayList的插入和删除元素的操作会花费线性时间,那么有没有插入和删除元素比较省时的集合呢,看下LinkedList这个实现。
        老样子,先看看它实现了那些接口。
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

        之前看过的接口不看了。先看下java.util.Deque。
public interface Deque<E> extends Queue<E>

        这个接口扩展了java.util.Queue,Queue也是Java Collections Framework中一个重要的接口,它表示了队列。当然队列本身也属于集合(java.util.Collection是更高层次的抽象)。
public interface Queue<E> extends Collection<E>{
    boolean add(E e);
    boolean offer(E e);
    E remove();
    E poll();
    E element();
    E peek();
}

        Queue提供了添加、删除和获取元素的方法,每种方法提供2个版本。如添加元素,add和offer都可以完成这个操作,区别在于add方法如果添加失败会抛出异常,而offer方法则会返回false。Queue接口只提供队列的抽象概念,但并没有定义元素的操作顺序。其实现可以提供先入先出或者先入后出(栈)这样的性质。

        大概了解了java.util.Queue后继续看java.util.Deque。既然Deque扩展了Queue,那它本质上也是队列喽。原来Deque是“double ended queue”的缩写,也就是双端队列的意思,单词读音为“deck”(蛋壳儿。。。)。 so,这个接口定义了在队列两端操作(添加、删除和获取)元素的方法。
public interface Deque<E> extends Queue<E> {
    void addFirst(E e);
    void addLast(E e);
    boolean offerFirst(E e);
    boolean offerLast(E e);
    E removeFirst();
    E removeLast();
    E pollFirst();
    E pollLast();
    E getFirst();
    E getLast();
    E peekFirst();
    E peekLast();
    boolean removeFirstOccurrence(Object o);
    boolean removeLastOccurrence(Object o);
    void push(E e);
    E pop();
    Iterator<E> descendingIterator();
}

        像Queue接口一样,Deque也对这些操作方法提供了2个版本。

        接下来看一下java.util.AbstractSequentialList这个抽象类,这个类的作用和java.util.AbstractList作用一样,提供一些“骨架”实现。区别在于这个类提供了“按次序访问”的基础,而AbstractList提供了“自由访问”的基础。也就是说,如果我们要实现一个基于链表的集合的话,可以继承这个类;要实现基于数组的集合的话,就继承AbstractList类。

        好了,在看LinkedList的源代码之前,还是先思考一下,如果自己实现LinkedList要怎么做。既然是链表,那么内部一定会有一个“链”,而“链”是由“环”组成,说明内部会有“环”这样的概念。每个环都和下一个环相扣,有两个特殊的环,首环和尾环。首先,没有任意一环的下一环是首环,尾环没有下一环;然后,首环和尾环上是不携带数据的(当然普通环也是可以保存null元素滴)。如果再从代码上考虑一下,每一个环都有下一个环的引用,这样可以构成一个链。但每个环也可以即有上一个环的引用,又有下一个环的引用,也可以构成链。它们有什么区别呢?其实这就是所谓的单向链表和双向链表,java.util.LinkedList内部使用双向链表实现。那可以使用单向链表实现吗?那就试试吧。
        首先要有头节点和尾节点,设想一下,如果没有它们,我们要保存的数据该放哪。。。然后还是要有一个size的私有变量,这样一些方法就好实现了。
/** 
 *   单向链表实现的LinkedList
 *   每个节点含有本节点元素及指向下一个节点的链,
 *   最后一个节点的next链为空。
 *
 * @author BrokenDreams
 */
public class LinkedList<E> 
	extends AbstractSequentialList<E> 
	implements List<E>,Deque<E>{

	//头节点
	private Entry<E> header = new Entry<E>(null, null);
	//尾节点
	private Entry<E> tail = new Entry<E>(null, null);

	private transient int size = 0;

	public LinkedList() {
		header.next = tail;
	}

	public LinkedList(Collection<? extends E> c){
		this();
		addAll(c);
	}

        “环”的实现很简单。是一个内部类。
private static class Entry<E> {
	E element;
	Entry<E> next;

	public Entry(E element, Entry<E> next) {
		super();
		this.element = element;
		this.next = next;
	}
}

        之前在总结ArrayList的时候,看到了当在集合尾部插入元素时,操作时间为常数时间(假设没有进行数组扩展);但当往集合首部插入元素时,内部数组中所有的元素都得往后移动一个位置(内部进行数组的拷贝),这样会花费O(n)的时间。我们看下单向链表实现里的情况。
	@Override
	public boolean add(E e) {
		if(size == 0){
			addAfter(e, header);
			return true;
		}
		Entry<E> node = header.next;
		while(node != null){
			if(node.next == tail){
				addAfter(e, node);
				return true;
			}
			node = node.next;
		}
		//never here
		return false;
	}

	private Entry<E> addAfter(E e, Entry<E> entry){
		Entry<E> newEntry = new Entry<E>(e, null);
		Entry<E> nextEntry = entry.next;
		entry.next = newEntry;
		newEntry.next = nextEntry;
		size++;
		modCount++;
		return newEntry;
	}

	@Override
	public void addFirst(E e) {
		addAfter(e, header);
	}

        可以看到,当在集合首部插入元素时,操作时间为常数时间;但当在集合尾部插入元素时,由于我们访问内部数据的入口只有内部的header和tail,又因为是单向链,我们要在集合尾部插入元素时,需要改变tail前一个元素的next,而要找到tail的前一个元素,需要从header开始往下找,所以操作时间还是O(n),看来单向链表还是不能达到我们的目的。。。

        好啦,还是看看LinkedList怎么玩儿的吧。
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    private transient Entry<E> header = new Entry<E>(null, null, null);
    private transient int size = 0;

    /**
     * Constructs an empty list.
     */
    public LinkedList() {
        header.next = header.previous = header;
    }

private static class Entry<E> {
	E element;
	Entry<E> next;
	Entry<E> previous;

	Entry(E element, Entry<E> next, Entry<E> previous) {
	    this.element = element;
	    this.next = next;
	    this.previous = previous;
	}
}

        在LinkedList中,只有一个首节点。当集合为空时,首节点的上一个节点和下一个节点都指向自己。可以想到,Linked内部的双向链表是一个环状结构,header作为起点和终点。
看一下LinkedList的添加元素方法:
    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
	        addBefore(e, header.next);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
	        addBefore(e, header);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
	        addBefore(e, header);
         return true;
    }

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

        再看看删除方法:
    /**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
	        return remove(header.next);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
	        return remove(header.previous);
    }

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

        可见在LinkedList首部和尾部添加和删除元素,操作时间都为常数时间。而在LinkedList中访问元素呢。
    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        return entry(index).element;
    }

    /**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        return remove(entry(index));
    }

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

        尽管做了一些优化,但当要访问元素越靠近链表中间位置时,要花费的时间越长。所以在LinkedList中,基于位置(Index)的操作都是低效的。
        OK,小总结一下。LinkedList内部采用双向链表实现,在表的两端进行插入和删除操作花费常数时间;基于位置的操作时低效的,当然查找元素也是低效的。
分享到:
评论
1 楼 continue_002 2013-08-16  
不错哦大飞,讲的很细了,如果有时间,你可以找个培训机构周末当javase老师,我来听课,我是途上(林)

相关推荐

Global site tag (gtag.js) - Google Analytics