【Java集合类】LinkedList源码分析(jdk1.8)

ArrayListLinkedListList接口的两种实现,具有相同的查找、插入、删除操作,只是底层的实现方式不一样。LinkedList是以双向链表形式实现的集合类。

其增删操作由于不需要移动底层数组数据,只需要修改链表节点指针,所以效率较高。但是随机访问时的定位操作效率较低,需要遍历链表节点。(ArrayList与之相反)


目录

  • 数据结构
    • 初始化
    • 扩容
  • 查找操作
  • 插入操作
  • 删除操作
  • 队列操作
  • 栈操作
  • 转化成数组
  • 迭代器实现

数据结构

底层基于双向链表实现的。并且元素允许 null 的存在。

其源码如下:

//没有空头节点的双向链表
    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;
        }
    }
    
    //表的长度
    transient int size = 0;

    /**
     * Pointer to first node.表的头节点指针
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node first;

    /**
     * Pointer to last node.表的尾节点指针
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node last;

初始化

由于链表,初始化时不需要指定表的长度。

/**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection c) {
        this();
        addAll(c);
    }

扩容

由于链表,扩容时只需要新建节点。


查找操作

1、通过索引查找元素(随机访问):

注意node(int index)函数:通过索引找到对应的节点。(后面很多方法都会用的)

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
/**
     * Returns the (non-null) Node at the specified element index.
     */
    //时间复杂度为n/2
    Node node(int index) {
        // assert isElementIndex(index);
        if (index < (size >> 1)) {
            Node x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

2、直接查找元素:

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

插入操作

在介绍插入操作前,首先介绍根据插入链表位置的不同,几种基本的插入链表方式:

  • (1)元素作为头节点插入链表:
/**
     * Links e as first element.
     */
    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++;
    }

	public void addFirst(E e) {
        linkFirst(e);
    }
  • (2)元素作为尾节点插入链表:
/**
     * Links e as last element.
     */
    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++;
    }

	public void addLast(E e) {
        linkLast(e);
    }
  • (3)元素作为节点e的前驱节点插入链表(相当于元素作为链表的中间节点):
  /**
         * Inserts element e before non-null Node succ.
         */
        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++;
        }

1、插入单个元素

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

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

        if (index == size)
            linkLast(element);
        else
            //在node(index)节点之前插入
            linkBefore(element, node(index));
    }

2、插入集合:

	public boolean addAll(Collection c) {
        return addAll(size, c);
    }
    
	//插入成第index个节点(= 即index节点后移 = 即在index节点之前插入)(index从0开始)
    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;
        //特殊情况:当索引index=size时,通过node(index)找不到节点,超过范围
        //(那为什么不把索引设置为index-1,即插入到index-1节点后?那插入到0节点之前也是特殊情况)
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            //找到第index个节点
            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;
        }
        //连接最后一个节点pred右边的所有链接
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

删除操作

首先介绍根据删除节点在链表位置的不同,几种基本的删除节点方式:

  • (1)删除头节点:
/**
     * Unlinks non-null first node f.
     */
    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;
    }

	public E removeFirst() {
        final Node f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
  • (2)删除尾节点:
/**
     * Unlinks non-null last node l.
     */
    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;
    }

	public E removeLast() {
        final Node l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
  • (3)删除中间节点:
/**
     * Unlinks non-null node x.
     */
    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;
    }

1、通过索引删除元素:

	 public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

2、删除指定元素:

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

队列操作

主要操作:

	//取队列头节点,但不删除
	//若first为空时,不抛出错误
    public E peek() {
        final Node f = first;
        return (f == null) ? null : f.item;
    }

    //若first为空时,抛出错误
    public E element() {
        return getFirst();
    }

    //出队列(头删)
    public E poll() {
        final Node f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

	//入队列(尾插)
    public boolean offer(E e) {
        return add(e);
    }


栈操作

主要操作:

	//入栈,头插
    public void push(E e) {
        addFirst(e);
    }

    //出栈,头删
    public E pop() {
        return removeFirst();
    }

转化成数组

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

@SuppressWarnings("unchecked")
    public  T[] toArray(T[] a) {
        if (a.length < size)
            //为什么用到反射?泛型类在运行时无法new实例化,只能在运行时得到class对象
            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;
    }

迭代器实现

首先了解什么是迭代器:

  • 深入理解Java中的迭代器

迭代器中fail-fast机制的实现:

  • fail-fast机制
  • 关于快速报错fail-fast想说的之fail-fast的实现原理(一)
private class ListItr implements ListIterator {
        private Node lastReturned;
        private Node 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() {
            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;
        }

        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

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

你可能感兴趣的:(java学习)