从源码分析LinkedList集合

x33g5p2x  于2021-12-06 转载在 其他  
字(6.9k)|赞(0)|评价(0)|浏览(368)

简介

LinkedList在java集合体系中的继承实现关系。

LinkedList就是把我们常说的链表结构,也是List中常用的一种集合。

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

LinkedList继承至AbstractSequentialList(AbstractList的子类),并且实现了List、Deque、Cloneable、Serializable接口,所以它也是可复制、可序列化的。

LinkedList底层使用双向链表进行数据的维护。初始长度为0,first和last指针分别指向首尾结点。

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;

其中Node结点的数据结构(双向链表结构)定义如下:

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

构造方法

LinkedList提供了两种构造方法:

LinkedList()

构造一个空列表

public LinkedList() {
    }

LinkedList(Collection<? extends E> c)

构造一个包含指定集合的元素的列表,按照它们由集合的迭代器返回的顺序。

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

常用方法

int size()

返回此列表中的元素数。

public int size() {
        return size;
    }

E getFirst()

返回列表中的第一个元素。

public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

E getLast()

返回列表中的最后一个元素。

public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

E removeFirst()

从列表中的删除并返回第一个元素。

public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

E removeLast()

从列表中的删除并返回最后一个元素。

public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

void addFirst(E e)

在列表的开头插入指定元素。

public void addFirst(E e) {
        linkFirst(e);
    }
    private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

void addLast(E e)

在列表的末尾插入指定元素。

public void addLast(E e) {
        linkLast(e);
    }
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

boolean contains(Object o)

如果列表中包含指定元素,返回true。

public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

int indexOf(Object o)

返回列表中指定元素第一次出现的索引,如果不存在该元素则返回-1。

public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

int lastIndexOf(Object o)

返回列表中指定元素最后一次出现的索引,如果不存在该元素则返回-1。

public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

向列表中添加元素

boolean add(E e)

将指定的元素追加到此列表的末尾。

public boolean add(E e) {
        linkLast(e);
        return true;
    }

void add(int index, E element)

在此列表中的指定位置插入指定的元素。

public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

boolean addAll(Collection<? extends E> c)

按指定集合的Iterator返回的顺序将指定集合中的所有元素追加到此列表的末尾。

public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

boolean addAll(int index, Collection<? extends E> c)

将指定集合中的所有元素插入到此列表中,从指定的位置开始。

public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        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;
            Node<E> newNode = new 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;
    }

void clear()

清空列表中的元素

public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        // more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

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

Object clone()

返回此ArrayList实例的浅拷贝。 (元素本身不被复制)

public Object clone() {
        LinkedList<E> clone = superClone();

        // Put clone into "virgin" state
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }

Object[] toArray()

以正确的顺序(从第一个到最后一个元素)返回一个包含此列表中所有元素的数组。

public Object[] toArray() {
        Object[] result = new Object[size];
        int i = 0;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

E get(int index)

获取指定索引的元素

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

E set(int index, E element)

用指定的元素替换此列表中指定位置的元素,返回原来的元素。

public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

队列相关的方法

LinkedList实现了Deque接口,所以LinkedList也包含了一些队列相关的方法。

E peek()

检索但不删除此列表的头。

public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

E element()

检索但不删除此列表的头。

public E element() {
        return getFirst();
    }

E poll()

检索并删除此列表的头。

public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

E remove()

检索并删除此列表的头。

public E remove() {
        return removeFirst();
    }

boolean offer(E e)

将指定的元素添加为此列表的尾部

public boolean offer(E e) {
        return add(e);
    }

boolean offerFirst(E e)

在列表的头部插入指定元素

public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

boolean offerLast(E e)

在列表的尾部插入指定元素。

public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

E peekFirst()

检索但不删除列表的第一个元素,如果为空,返回null。

public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

E peekLast()

检索但不删除列表的最后一个元素,如果为空,返回null。

public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

E pollFirst()

检索并删除列表的第一个元素,如果为空,返回null。

public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

E pollLast()

检索并删除列表的最后一个元素,如果为空,返回null。

public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

void push(E e)

列表的头部插入指定元素。

public void push(E e) {
        addFirst(e);
    }

E pop()

删除并返回列表的第一个元素

public E pop() {
        return removeFirst();
    }

相关文章