频道栏目
首页 > 资讯 > Android > 正文

LinkedList源码分析

16-06-22        来源:[db:作者]  
收藏   我要投稿

LinkedList类继承了AbstractSequentialList< E >抽象类并实现了List接口。在AbstractSequentialList类中,其实主要是实现一些关于索引的方法。因此LinkedList中也支持“随机访问”。但这种随机是伪随机的,稍后我们可以看到。这里我结合今天下午我参加的一场面试来简要说一下关于LinkedList和ArrayList的一些问题。

ArrayList底层是动态数组实现的。随机访问的速度较快,即支持高效的随机访问,且在list末尾添加元素的开销基本是固定的(如果不涉及到扩容的情况)。 LinkedList底层是链表实现。因此删除和添加操作是比较占优势的。 List接口下都是有序的集合。 实际使用中,ArrayList使用的较多,因为实际使用时一般会有内存大小的限制(这是那个公司面试我的那个技术人员说的)。(难道是LinkedList不好控制使用的内存???) 当插入较多,但是随机查找较少的时候,用LinkedList可能性能会比较好。反之,用ArrayList。不过二者的使用均视实际情况而定。

下面是源码分析:


package java.util;

import java.util.function.Consumer;


public class LinkedList
    extends AbstractSequentialList
    implements List, Deque, Cloneable, java.io.Serializable
{
    transient int size = 0;//代表LinkedList中的节点个数

    transient Node first;

    transient Node last;//从这两个成员变量可以看出来,LinkedList是双向链表

    public LinkedList() {
    }


    public LinkedList(Collection c) {
        this();
        addAll(c);
    }

    //将e构成的节点作为首节点
    private void linkFirst(E e) {
        final Node f = first;
        final Node 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 l = last;
        final Node newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

    //某个节点前添加节点
    void linkBefore(E e, Node succ) {
        // assert succ != null;
        final Node pred = succ.prev;
        final Node newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

    //删除首节点并返回首节点中的数据
    private E unlinkFirst(Node f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node 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;
    }

    //删除尾节点并返回尾节点中的数据
    private E unlinkLast(Node l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node 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;
    }

    //删除指定的某个节点并返回该节点中的数据
    E unlink(Node x) {
        // assert x != null;
        final E element = x.item;
        final Node next = x.next;
        final Node 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 f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
    //得到尾节点
    public E getLast() {
        final Node l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    //删除首节点(与前面相比只是增加了null控制逻辑)
    public E removeFirst() {
        final Node f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    //同上
    public E removeLast() {
        final Node 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 x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }


    public boolean addAll(Collection c) {
        return addAll(size, c);
    }

    //将集合c中的数据添加进LinkedList,index为插入的位置,由此可见,添加方法总是从最后开始添加。
    public boolean addAll(int index, Collection c) {
        checkPositionIndex(index);

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

        Node 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 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() {
        // 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
        //全部置为null,help GC;
        for (Node x = first; x != null; ) {
            Node next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }


    // Positional Access Operations


    public E get(int index) {
        checkElementIndex(index);//这里是索引位置检查
        return node(index).item;
    }

    将某个节点的值替换并返回旧值
    public E set(int index, E element) {
        checkElementIndex(index);//索引合法性判断
        Node x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

    //将E节点加入链表,其索引为index
    public void add(int index, E element) {
        checkPositionIndex(index);//注意:这里是插入位置检查,index可以取size,即尾节点的下一个位置也可以取的。
                                  //跟上面进行的索引合法性判断不同
        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));
    }
    //获得指定位置处的node
    Node node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node x = first;
            for (int i = 0; i < index; i++)//无论寻找哪个节点,都是从首节点开始循环查找。且首节点的索引号为0.
                x = x.next;
            return x;
        } else {
            Node x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

    //****************************** Search Operations*****************************
    //从首节点开始查找并返回某个指定数据的索引,可以看出LinkedList中允许null属性的存在
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node 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 x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

    // ************************Queue operations************************.

    //返回首节点中的数据(首节点可以为null)
    public E peek() {
        final Node f = first;
        return (f == null) ? null : f.item;
    }
    //返回首节点,但是前期是要保证首节点不能为null
    public E element() {
        return getFirst();
    }

    //返回首节点并且将其删除,相当于出队列。
    public E poll() {
        final Node f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    //简单的删除头结点
    public E remove() {
        return removeFirst();
    }
    //相当于入队列
    public boolean offer(E e) {
        return add(e);
    }

    // ************Deque operations**************
    //*************双端操作,应用与双向队列******

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


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


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


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


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

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


    public void push(E e) {
        addFirst(e);
    }
    //出栈
    public E pop() {
        return removeFirst();
    }

    //删除第一个值为o的节点
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    //删除最后一个值为o的节点
    public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    //**************下面是迭代器*****************
    public ListIterator listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }

    //私有内部类
    private class ListItr implements ListIterator {
        private Node lastReturned;//上一个返回的节点
        private Node next;//下一个节点
        private int nextIndex;//下一个节点的索引
        private int expectedModCount = modCount;//防止使用迭代器遍历时LinkedList发生改变

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        public boolean hasNext() {
            return nextIndex < size;
        }
        //迭代器实现返回下一个节点的值
        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }

        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }

        public int nextIndex() {
            return nextIndex;
        }

        public int previousIndex() {
            return nextIndex - 1;
        }

        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }

        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }
        //调用迭代器这个add方法也可能导致异常产生,而在ArrayList中调用该方法不会产生异常
        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;//在最后这个位置,ArrayList的处理是:expectedModCount = modCount;这里区别很大
        }
        //consumer是一个功能函数接口
        //这也是1.8新增加的特性
        //Consumer接口中有2个方法,有且只有一个声明为accept(T t)的方法,接收一个输入参数并且没有返回值。
        //然后根据输入参数对对象进行一些操作
        //下面这个方法是通过Consumer接口对集合中的所有对象进行统一的操作
        public void forEachRemaining(Consumer action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    //私有内部节点类
    private static class Node {
        E item;
        Node next;
        Node prev;

        Node(Node prev, E element, Node next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

    public Iterator descendingIterator() {
        return new DescendingIterator();
    }

    private class DescendingIterator implements Iterator {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    @SuppressWarnings("unchecked")
    private LinkedList superClone() {
        try {
            return (LinkedList) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    //执行的是浅克隆,即只是克隆了引用,而没有克隆实例对象。
    public Object clone() {
        LinkedList 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 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 x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

    //这部分跟ArrayList基本一样
    @SuppressWarnings("unchecked")
    public  T[] toArray(T[] a) {
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        for (Node x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }
    //支持序列化传输
    private static final long serialVersionUID = 876323262645176354L;

    //序列化传输的写操作
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (Node x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }

    //序列化传输的读操作
    @SuppressWarnings("unchecked")
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            linkLast((E)s.readObject());
    }

    //1.8增加的新特性
    @Override
    public Spliterator spliterator() {
        return new LLSpliterator(this, -1, 0);
    }

    /** A customized variant of Spliterators.IteratorSpliterator */
    static final class LLSpliterator implements Spliterator {
        static final int BATCH_UNIT = 1 << 10;  // batch array size increment
        static final int MAX_BATCH = 1 << 25;  // max batch array size;
        final LinkedList list; // null OK unless traversed
        Node current;      // current node; null until initialized
        int est;              // size estimate; -1 until first needed
        int expectedModCount; // initialized when est set
        int batch;            // batch size for splits

        LLSpliterator(LinkedList list, int est, int expectedModCount) {
            this.list = list;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getEst() {
            int s; // force initialization
            final LinkedList lst;
            if ((s = est) < 0) {
                if ((lst = list) == null)
                    s = est = 0;
                else {
                    expectedModCount = lst.modCount;
                    current = lst.first;
                    s = est = lst.size;
                }
            }
            return s;
        }

        public long estimateSize() { return (long) getEst(); }

        public Spliterator trySplit() {
            Node p;
            int s = getEst();
            if (s > 1 && (p = current) != null) {
                int n = batch + BATCH_UNIT;
                if (n > s)
                    n = s;
                if (n > MAX_BATCH)
                    n = MAX_BATCH;
                Object[] a = new Object[n];
                int j = 0;
                do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
                current = p;
                batch = j;
                est = s - j;
                return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
            }
            return null;
        }

        public void forEachRemaining(Consumer action) {
            Node p; int n;
            if (action == null) throw new NullPointerException();
            if ((n = getEst()) > 0 && (p = current) != null) {
                current = null;
                est = 0;
                do {
                    E e = p.item;
                    p = p.next;
                    action.accept(e);
                } while (p != null && --n > 0);
            }
            if (list.modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

        public boolean tryAdvance(Consumer action) {
            Node p;
            if (action == null) throw new NullPointerException();
            if (getEst() > 0 && (p = current) != null) {
                --est;
                E e = p.item;
                current = p.next;
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

}

总结:

LinkedList是双向链表。 size是链表节点的个数。 根据索引查找数据时,首节点的索引为0。 LinkedList中可以存储null值节点。
相关TAG标签
上一篇:python从数据库中获取utf8格式的中文数据输出时变成问号或乱码
下一篇:汇编实现排序——希尔排序
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站