Java 集合類——Collections(2)

LinkedList

LinkedList的定義:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{...}複製代碼

  • LinkedList<E>:說明它支持泛型
  • extends AbstractSequentialList<E>:說明LinkedList不支持隨機訪問,只支持按次序訪問
  • 實現了List<E>接口:說明它支持集合的通常操做
  • 實現了Deque<E>接口:說明它可用做隊列和雙向隊列
  • 實現了Cloneable、Serializable:可調用clone()方法和可序列化。

transient int size = 0;

/**
 * Pointer to first node.
 * Invariant: (first == null && last == null) || 
 *            (first.prev == null && first.item != null)
 */
transient Node<E> first;

/**
 * Pointer to last node.
 * Invariant: (first == null && last == null) ||
 *            (last.next == null && last.item != null)
 */
transient Node<E> last;

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

複製代碼

Node是雙向鏈表節點所對應的數據結構,包括的屬性是:當前節點的值,上一個節點,下一個節點。java

構造方法

public LinkedList() {
}

//接收一個Collection參數c,調用第一個構造方法,並把c中全部元素添加到鏈表中
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}複製代碼

經常使用方法node

  • removeFirst():刪除表頭元素
  • removeLast():刪除表尾元素
  • addFirst(E e):在表頭插入指定元素
  • addLast(E e):在表尾插入指定元素
  • contains(Object o):判斷鏈表是否包含指定對象
  • add(E e):在表尾插入指定元素
  • remove(Object o):正向遍歷鏈表,刪除第一個值爲指定對象的節點
  • addAll(Collection<? extends E> c):在表尾插入指定集合
  • clear():清除鏈表中的全部元素

LinkedList的遍歷方式

LinkList遍歷不用for循環,由於用迭代器iterator遍歷比for快。數組

for循環遍歷:bash

for(int i=0; i<list.size(); i++) {
    list.get(i);
}複製代碼

//LinkedList的get方法源碼
public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

Node<E> node(int index) {
    // assert isElementIndex(index);
    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}複製代碼

迭代器遍歷:數據結構

List<Integer> list = new LinkedList<>();
Iterator<Integer> iterator = list.listIterator();
while (iterator.hasNext()) {
    Integer i =  iterator.next();
}複製代碼

//next方法
public E next() {
    checkForComodification();
    if (!hasNext())
        throw new NoSuchElementException();
    lastReturned = next;
    next = next.next;
    nextIndex++;
    return lastReturned.item;
}複製代碼

從源碼能夠看出,LinkedList若是用for循環遍歷,get方法裏面會再次使用循環遍歷鏈表,時間複雜度是O(n²);若是有迭代器遍歷,由於next的存在,獲得當前項不須要時間,因此只須要使用一次循環,時間複雜度是O(n)。ui

ArrayList和LinkedList的區別

  • ArrayList是基於動態數組的數據結構,LinkedList是基於鏈表(雙向鏈表)的數據結構
  • 對於隨機訪問,ArrayList要比LinkedList方便,由於LinkedList是移動指針
  • 關於增長和刪除操做,LinkedList比較方便,ArrayList要慢慢移動元素位置(索引)


參考資料:this

Java8源碼-LinkedListspa

爲何使用迭代器iterator遍歷Linkedlist要比普通for快.net

相關文章
相關標籤/搜索