LinkedList源码详解

     LinkedList也和ArrayList一样实现了List接口,因为它是基于双向链表实现的,所以其插入和删除效率比ArrayList高。同时基于链表也决定了它在随机访问方面要比ArrayList逊色(因为要移动指针)。除此之外,LinkedList还提供了一些可以使其作为栈、队列、双端队列的方法。

      LinkedList同样是非线程安全的,只适合在单线程下使用。LinkedList实现了Serializable接口,故它支持序列化,能够通过序列化传输,实现了Cloneable接口,能被克隆。

import java.util.function.Consumer;
import java.util.*;

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
	//LinkedList中元素个数
    transient int size = 0;
    //头结点
    transient Node<E> first;
    //尾结点
    transient Node<E> last;
    //默认构造函数:创建一个空的链表
    public LinkedList() {
    }
    //包含指定集合的构造函数
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
    
    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++;
    }

    //在非空结点前插入指定元素
    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++;
    }

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

    
    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;
    }
    //获得LinkedList的第一个元素
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
    //获得LinkedList的最后一个元素
    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);
    }
   
    //将元素添加到LinkedList的起始位置
    public void addFirst(E e) {
        linkFirst(e);
    }

    //将元素添加到LinkedList的结束位置
    public void addLast(E e) {
        linkLast(e);
    }

    //判断LinkedList是否包含指定元素
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }
    
    //返回LinkedList的大小
    public int size() {
        return size;
    }

    //将元素添加到LinkedList(末尾)
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    //从LinkedList中删除指定的值
    public boolean remove(Object o) {
    	//指定元素为null的情况
        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;
    }
    //将指定集合添加到LinkedList中
    //实际上,是添加到双向链表的末尾
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
    
    //从双向链表的index开始,将指定集合添加到双向链表中
    public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);
       //将集合转化为Object对象数组
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;
      
        Node<E> pred, succ;
        //如果index等于size
        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() {
        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;
    }
    
    Node<E> node(int index) {
        // assert isElementIndex(index);
        //若index < 双向链表长度的1/2,则从前往后查找
    	//否则,从后往前查找
        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;
        }
    }

    //设置指定位置上的值
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

    //在指定位置添加结点,且结点的值为element
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    //删除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));
    }

    

    /*查找操作*/

    //从前往后查找,返回值为对象(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;
    }

    //从前往后查找,返回值为对象(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;
    }

    // 队列操作

    //返回第一个结点
    //若LinkedList的大小为0,返回null
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    //返回第一个结点
    //若LinkedList的大小为0,则抛出异常
    public E element() {
        return getFirst();
    }

    //删除并返回第一个结点
    //若LinkedList的大小为0,返回null
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    //删除并返回第一个结点
    //若LinkedList的大小为0,则抛出异常
    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;
    }

    //返回(并不删除)第一个结点
    //若LinkedList的大小为0,则返回null
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

    //返回(并不删除)最后一个结点
    //若LinkedList的大小为0,则返回null
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    //删除并返回第一个结点
    //若LinkedList的大小为0,则返回null
    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);
    }

    //将e插入到双向链表开头
    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<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;
    }

    //返回index到末尾的全部结点对应的ListIterator对象(List迭代器)
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
    }
    //List迭代器
    private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;

        ListItr(int index) {
        	// assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }
        
        //判断是否存在下一个元素
        public boolean hasNext() {
            return nextIndex < size;
        }
        //获取下一个元素
        public E next() {
            //fail-fast机制
            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<E> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }
        
        //设置当前结点为e
        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }
        
        //将e添加到当前结点的前面
        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }
        
        
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }
        //fail-fast机制
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    
    //双向链表采用的数据结构
    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;
        }
    }

    /**
     * @since 1.6
     */
    //反向迭代器
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }
    
    //反向迭代器实现类
    private class DescendingIterator implements Iterator<E> {
        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<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    //返回LinkedList的浅克隆
    public Object clone() {
        LinkedList<E> clone = superClone();

        // Put clone into "virgin" state
        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;
    }

    //返回LinkedList的Object对象数组
    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的模板数组
    @SuppressWarnings("unchecked")
    public <T> 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<E> 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;

    //将LinkedList的大小以及所有元素值都写入到输出流中
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        
        s.writeInt(size);

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

    //先将LinkedList的容量读出,然后将所有的元素对象读出
    @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.从源码中很明显可以看出,LinkedList的实现是基于双向链表的。

2.在查找和删除某元素时,源码中都划分为该元素为null和不为null两种情况来处理,LinkedList中允许元素为null。

3.LinkedList是基于链表实现的,因此不存在容量不足的问题,所以这里没有扩容的方法。

4.LinkedList是基于链表实现的,因此插入删除效率高,查找效率低。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值