Java容器二:LinkedList

来源:互联网 发布:电驴默认端口 编辑:程序博客网 时间:2024/05/17 01:02

LinkedList

List,Deque,Cloneable,Serializable

–>AbstractSequentialList –>AbstractCollection –>AbstractList


LinkedList同样是fail-fast的。

成员变量

    // list的长度    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;

节点

LinkedList内部使用双向节点实现

private static class Node<E> {    E item;    Node<E> next;    Node<E> prev;}

增加删除操作

LinkedList定义了头和尾节点,进行增删操作都要考虑对头部节点和尾部节点的操作

transient Node<E> first;transient Node<E> last;

如在链表中删除一个节点

// 供内部调用的函数,保证x一定非空   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--;   // 和ArrayList类似,实现线程安全检测       modCount++;       return element;   }

通过Index得到Node

LinkedList需要通过Index得到Node时基本都靠内部的node函数进行得到,若index在前半段,则从前往后查找,若index在后半段,则从后往前查找。

 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;     } }
0 0
原创粉丝点击