java源码品读(13)— LinkedList

版权声明:转载的话请注明原文章地址,谢谢 https://blog.csdn.net/m0_37664906/article/details/82707908

概述

之前说过了LinkedList的相关的父类,今天我们来看看LinkedList本身的内容。
众所周知,ArrayList和LinkedList是我们工作中经常用到的两种集合,这两兄弟也经常会被拿到一起来做比较,ArrayList因其底层的数组结构,所以其改和查的效率相当高,但是增和删的效率就相对较低,而LinkedList则正好相反,增和删都因其底层的链式结构,效率很高,而改和查就需要先定位到目标的节点,所以效率较低。
至于细节的东西到底是什么,我们就要从它的源码中一点一点去摸索。

  • 成员属性
	//集合大小
    transient int size = 0;
	//集合中链表的第一个节点
    transient Node<E> first;
	//集合中链表的最后一个节点
    transient Node<E> last;

三者都使用transient关键字修饰,套路跟之前我们看过的ArrayList一致,由本类中的私有方法writeObject和readObject提供序列化的支持,同时省去三个属性在序列化时占用的空间。

  • 构造方法
    public LinkedList() {
    }
    
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

提供两个构造器,一个无参构造器和一个有参构造器,有参构造器需要传入一个集合,将集合中的元素加入LinkedList中,如果集合为空的话,会抛出异常。

  • 内部类

LinkedList中包含几个内部类ListItr(LinkedList的迭代器)、Node(LinkedList用于存储元素的节点)、DescendingIterator(LinkedList的倒序迭代器)、LLSpliterator(LinkedList的并行迭代器)
三个迭代器在这里就不细说了,跟ArrayList的套路大致相同,只是其中的有些方法使用的是LinkedList中的相应方法。这个如果有同学不清楚的话可以移步 ArrayList迭代器ArrayList并行迭代器 细细理解。

下面我们来看一下LinkedList中比较重要的一个内部类: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;
    }
}

节点的设计相对简单但是也实用,满足双向链表的数据存储要求。

  • 成员方法
	//将指定元素链接为头元素
	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 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++;
    }
    //在指定节点succ前面插入e
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
	//将头元素取出并返回(需要保证指定元素跟头元素相等且不为null)
    private E unlinkFirst(Node<E> f) {
        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;
    }
    //将尾元素取出并返回(需要保证指定元素跟尾元素相等且不为null)
    private E unlinkLast(Node<E> l) { 
        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;
    }
    //取出指定元素(需要保证指定元素不为null)
    E unlink(Node<E> x) {
        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;
    }
    //获取头元素
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
    //获取尾元素
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
    //删除并获取头元素
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
	//删除并获取尾元素
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    //头部增加指定元素
    public void addFirst(E e) {
        linkFirst(e);
    }
    //尾部增加指定元素
    public void addLast(E e) {
        linkLast(e);
    }
    //队列中是否存在指定元素
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
    //集合大小
    public int size() {
        return size;
    }
    //尾部增加指定元素
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    //删除指定元素在集合中第一个实例
    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;
    }
    //尾部增加指定集合的所有元素
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, 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;
    }
    //清空所有元素
    public void clear() {
        //清空元素属性,帮助GC回收
        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++;
    }
    //获取指定位置元素
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    //将制定元素放到指定位置(替换原有元素)
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }
    //将制定元素放到指定位置(原有元素后移)
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    //删除并返回指定位置的元素
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
    //查看指定位置是否有元素(根据索引)
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }
    //查看指定位置是否有元素(根据位置)
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }
	//数组越界错误信息
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
	//检查元素下标是否合规
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
	//检查元素位置是否合规
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
	//获取指定元素第一次出现的索引
    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;
    }
	//获取指定元素最后一次出现的索引
    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;
    }
	//返回列表的头元素,但是不会删除列表中的头元素(无异常)
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }
	//返回列表的头元素,但是不会删除列表中的头元素,没有头元素会抛出异常
    public E element() {
        return getFirst();
    }
	//取出并返回头元素
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
	//删除头元素,若没有会抛出异常
    public E remove() {
        return removeFirst();
    }
	//尾部添加一个元素
    public boolean offer(E e) {
        return add(e);
    }
	//头部添加一个元素
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }
	//尾部添加一个元素
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }
	//返回头元素
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }
	//返回尾元素
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }
	//取出并返回头元素
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
	//取出并返回尾元素
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }
	//头部添加一个元素
    public void push(E e) {
        addFirst(e);
    }
	//取出并返回头元素,无头元素会抛出异常
    public E pop() {
        return removeFirst();
    }
	//移除第一个出现的指定元素
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }
	//移除最后一次出现的指定元素
    public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
	//获取一个从指定下标开始的迭代器
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }
	//获取一个倒序的迭代器
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }
	//使用Object的克隆方法进行复制    
    @SuppressWarnings("unchecked")
    private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }
	//自己的克隆方法,元素相同,修改次数重新计算
    public Object clone() {
        LinkedList<E> clone = superClone();
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);
        return clone;
    }
	//自己的克隆方法,元素相同,修改次数重新计算
    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;
    }
  • 方法总结

LinkedList中存在很多相似的方法,在上面的源码中我们大致可以总结出下面的这些东西,以方便以后的使用

增加方法 获取方法 删除方法 备注
add(E),addFirst(E),addLast(E) get(index),getFirst(),getLast() remove(E),removeFirst(),removeLast() 获取删除集合中无元素会抛出异常
push(),offer(E),offerFirst(E),offerLast(E) peek(),peekFirst(),peekLast() pop(),poll(),pollFirst(),pollLast() 获取删除集合中无元素返回null

随机访问慢的原因:

    Node<E> node(int 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;
        }
    }

查找指定位置的节点时,根据索引的位置进行正向或者是逆向的循环,只到找到相应的节点。而不是像ArrayList一样直接就能找到相应的位置。
添加和删除的操作,都是在队列的首尾进行,所以相当的省力,而ArrayList的删除和添加不仅仅需要找到指定的位置,而且还夹杂着一些元素移位的操作,所以就相对耗时较长。

猜你喜欢

转载自blog.csdn.net/m0_37664906/article/details/82707908