LinkedList源码学习

LinkedList是List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。

在添加和删除元素上的效率要比ArrayList高很多,但是在查询效率上低。

LinkedList的属性说明:

  • private transient Entry<E> header = new Entry<E>(null, null, null);
  • private transient int size = 0;
  • protected transient int modCount;
    继承自AbstractList的属性。表示已从结构上修改 此列表的次数。

链表以虚拟节点header元素构造了一个环形,header标记位置,header的next属性指向链表的头,header的previous属性指向链表的尾。

内部类Entry源码: 

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对象

 将Entry类型的对象header的属性next和previous的值指向为其本身header。

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

 增加元素到链表尾部

public boolean add(String e) {
		addBefore(e, header);
		return true;
	}
private Entry addBefore(String e, Entry entry) {
        //entry是链表中要在其前面插入的节点
         //创建一个新节点,值为要保持到列表中的元素, next属性指向entry,previous属性指向entry的previous节点
         //因为新节点要在entry前面插入,所以新节点的下一个就是entry,上一个就是entry的原来的上一个   
	Entry newEntry = new Entry(e, entry, entry.previous);
        //链表中新节点的上一个元素的next属性指向新节点
	newEntry.previous.next = newEntry;
        //链表中新节点的下一个元素的previous属性指向新节点
	newEntry.next.previous = newEntry;

	return newEntry;
}

返回列表中指定位置的元素

public E get(int index) {
        return entry(index).element;
    }
/**
     * 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;
        // >> 右移运算符,num >> 1,相当于num除以2
        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;
    }

  

猜你喜欢

转载自qiyanb.iteye.com/blog/2199566
今日推荐