《Java集合类2》讲解LinkedList

标题 : LinkedList

概述
LinkedList与ArrayList一样实现List接口。 只是ArrayList是List接口的大小可变数组的实现;&LinkedList是List接口链表的实现。基于链表实现的方式使得LinkedList在插入和删除时更优于ArrayList,而随机访问则没有ArrayList效率快。

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

此类实现 Deque 接口,为 add、poll 提供先进先出队列操作,以及其他堆栈和双端队列操作。
所有操作都是按照双重连接列表的需要执行的。在列表中编索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端)。
同时,与ArrayList一样此实现不是同步的。

源码分析
1、LinkedList源码定义:

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

从这段代码中可以看出LinkedList继承AbstractSequentialList,实现List、Deque、Cloneable、Serializable。其中AbstractSequentialList提供了 List 接口的骨干实现,从而最大限度地减少了实现受“连续访问”数据存储(如链接列表)支持的此接口所需的工作,从而以减少实现List接口的复杂度。Deque一个线性 collection,支持在两端插入和移除元素,定义了双端队列的操作。

2、两个基本属性:size、header

   transient int size = 0; 
   transient Entry header =new Entry(null,null,null);

其中size表示的LinkedList的大小,header表示链表的表头,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;
    }
}
  上面为Entry对象的源代码,Entry为LinkedList的内部类,它定义了存储的元素。
  该元素的前一个元素、后一个元素,这是典型的双向链表定义方式。

3、构造方法
LinkedList提供了两个构造方法:LinkedList()和LinkedList(Collection<? extends E> c)

/**
 * 构造一个空列表.
 */
public LinkedList() {
}

/**
  * 构造一个包含指定 collection 中的元素的列表,这些元素按其 collection 的迭代器
  * 返回的顺序排列.
 */
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

LinkedList()构造一个空列表。里面没有任何元素,仅仅只是将header节点的前一个元素、后一个元素都指向自身。
LinkedList(Collection<? extends E> c): 构造一个包含指定 collection 中的元素的列表,这些元素按其 collection 的迭代器返回的顺序排列。该构造函数首先会调用LinkedList(),构造一个空列表,然后调用了addAll()方法将Collection中的所有元素添加到列表中。以下是addAll()的源代码

/**
 *  添加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器
 *  返回这些元素的顺序。
 */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
    
/**
 * 将指定 collection 中的所有元素从指定位置开始插入此列表。其中index表示在其中
 * 插入指定collection中第一个元素的索引
 */
public boolean addAll(int index, Collection<? extends E> c) {
    checkPositionIndex(index);//检查下标合法性

    Object[] a = c.toArray();
    int numNew = a.length;   //插入元素的个数
    //若插入的元素为空,则返回false
    if (numNew == 0)
        return false;

    //获取插入位置的节点succ,若插入的位置在size处,则是头节点,否则获取index位置处的节点
    //插入位置的前一个节点pred,在插入过程中需要修改该节点的next引用:指向插入的节点元素
    LinkedList.Node<E> pred, succ;
    if (index == size) {
        succ = null;
        pred = last;
    } else {
        succ = node(index);
        pred = succ.prev;
    }

    //执行插入动作
    for (Object o : a) {
        @SuppressWarnings("unchecked") E e = (E) o;
        //构造一个节点newNode,这里已经执行了插入节点动作同时修改了相邻节点的指向引用
        LinkedList.Node<E> newNode = new LinkedList.Node<>(pred, e, null);
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        //修改插入位置的前一个节点,这样做的目的是将插入位置右移一位,保证后续的元素
        //是插在该元素的后面,确保这些元素的顺序
        pred = newNode;
    }

    if (succ == null) {
        last = pred;
    } else {
        pred.next = succ;
        succ.prev = pred;
    }
    //修改容量大小
    size += numNew;
    modCount++;
    return true;
}addAll()方法中,涉及到了两个方法:
  一个是checkPositionIndex(int index),该方法为LinkedList的私有方法,主要是用来检查下标合法性;
  另一个是node(int index),该方法主要是用来查找index位置的节点元素。
/*
 * 判断下标合法性,合法就返回true,否则抛异常。
 */
private void checkPositionIndex(int index) {
    if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
    return index >= 0 && index <= size;
}

/**
 * 返回指定位置(若存在)的节点元素
 */
    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;
    }
}

从该方法有两个遍历方向中就可以看出:LinkedList是双向链表,这也是在构造方法中为什么需要将header的前、后节点均指向自己。
所以只需要知道:LinkedList是双向链表。

LinkedList中几个常用方法的源码分析
【增】

/*
 * add(E e): 将指定元素添加到此列表的结尾。
 */
public boolean add(E e) {
    linkLast(e);
    return true;
}
   方法调用linkLast方法,然后直接返回true,对于linkLast()而已,它为LinkedList的私有方法
/**
 * Links e as first element.
 */
private void linkFirst(E e) {
    final Node<E> f = first;
    //构造一个新结点 newEntry,
    final Node<E> newNode = new Node<>(null, e, f);
    first = newNode;
    //修改newNode 的前后节点的引用,确保其链表的引用关系是正确的
    if (f == null)
        last = newNode;
    else
        f.prev = newNode;
    size++; //容量+1
    modCount++; //修改次数+1
}   

在linkLast方法中无非就是:构建一个新节点newNode ,然后修改其前后的引用。
LinkedList还提供了其他的增加方法:

  add(int index, E element):在此列表中指定的位置插入指定的元素。
  addAll(Collection<? extends E> c):添加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器返回这些元素的顺序。
  addAll(int index, Collection<? extends E> c):将指定 collection 中的所有元素从指定位置开始插入此列表。
  addFirst(E e): 将指定元素插入此列表的开头。
  addLast(E e): 将指定元素添加到此列表的结尾。

【删】

  remove(Object o):从此列表中移除首次出现的指定元素(如果存在)。该方法的源代码如下:

public boolean remove(Object o) {
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

该方法首先会判断移除的元素是否为null,然后迭代这个链表找到该元素节点,最后调用remove(Node e),remove(Node e)是LinkedList中所有移除方法的基础方法,如下:

/*
 * 从这个列表中删除指定位置的元素。
 */
public E remove(int index) {
    checkElementIndex(index);//检查下标的合法性,上面已经分析过
    return unlink(node(index));
}

E unlink(Node<E> x) {
    // assert x != null;
    //保留被移除的元素:要返回
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}
  clear(): 从此列表中移除所有元素。
  remove():获取并移除此列表的头(第一个元素)。
  remove(int index):移除此列表中指定位置处的元素。
  remove(Objec o):从此列表中移除首次出现的指定元素(如果存在)。
  removeFirst():移除并返回此列表的第一个元素。
  removeFirstOccurrence(Object o):从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表时)。
  removeLast():移除并返回此列表的最后一个元素。
  removeLastOccurrence(Object o):从此列表中移除最后一次出现的指定元素(从头部到尾部遍历列表时)。

【改】

/*
 *  将指定的元素替换指定位置的元素; 
 */
public E set(int index, E element) {
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

【查】

/**
 * 对于查找方法的源码就是迭代,比对,然后就是返回当前值。
 * get(int index):返回此列表中指定位置处的元素。
 * getFirst():返回此列表的第一个元素。
 * getLast():返回此列表的最后一个元素。
 * indexOf(Object o):返回此列表中首次出现的指定元素的索引,如果此列表中不包含该元素,则返回 -1。
 * lastIndexOf(Object o):返回此列表中最后出现的指定元素的索引,如果此列表中不包含该元素,则返回 -1。
 */
public E get(int index) {
    checkElementIndex(index);//检查下标的合法性,上面已经分析过
    return node(index).item; //查找index位置的节点元素。
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章