美文网首页
LinkedList源码分析

LinkedList源码分析

作者: 天草二十六_简村人 | 来源:发表于2019-09-26 09:25 被阅读0次

一、UML


UML.png

1、继承抽象类AbstractSequentialList
它又继承于抽象类AbstractList,增加了利用Iterator遍历器实现链表的操作。
2、实现List接口
为什么抽象类实现了该接口,LinkedList还要再次实现一遍呢?
https://stackoverflow.com/questions/2165204/why-does-linkedhashsete-extend-hashsete-and-implement-sete
3、实现Deque接口
它又继承于接口Queue,让LinkedList很好地实现队列。LinkedList是一个双向链表。
4、实现Cloneable接口
实现了浅拷贝

二、属性
记录链表的大小,首节点,尾节点。

   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;

三、构造方法

/**
     * 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<? extends E> c) {
        this();
        addAll(c);
    }

四、普通方法
1、link和unlink等6个辅助方法,包括3个link和3个unlink

    /**
     * Links e as first element.
     */
    private void linkFirst(E e) {
// 记录头节点
        final Node<E> f = first;
// 新建一个节点,作为头节点,它的前驱节点为null,  内容为e,  后驱节点为f(即头节点)
        final Node<E> newNode = new Node<>(null, e, f);
//把上一步新建的节点作为新的头节点
        first = newNode;
// 如果头节点为空,也就是说e是第一个元素,newNode既是头节点,也是尾节点。
        if (f == null)
            last = newNode;
        else
// 之前的头节点的前驱节点就是新的头节点
            f.prev = newNode;
        size++;
        modCount++;
    }

    /**
     * Links e as last element.
     */
    void linkLast(E e) {
// 操作的思路和linkFirst类似
        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++;
    }

    /**
     * Inserts element e before non-null Node succ.
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null; 
// 这里是不是把succ取名作targetNode比较好?
        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++;
    }

// 上述三个link方法,下面是三个unlink方法。
    /**
     * Unlinks non-null first node f.
     */
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
// 取出要删除的节点的内容和后驱节点。因为是删除头节点,所以它是没有前驱节点的。
        final E element = f.item;
        final Node<E> next = f.next;
// 被删除节点的内容赋值为null, 也不指向后驱节点。
        f.item = null;
        f.next = null; // help GC
// 被删节点的后驱节点,接班为新的头节点
        first = next;
// 如果被删节点的后驱节点为null,说明整个链表就一个f元素,被删除后,首节点的后驱节点就也为null。
        if (next == null)
            last = null;
        else
// next 已经身为新的首节点了,前驱节点自然也就为null
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

    /**
     * Unlinks non-null last node 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;
    }

    /**
     * Unlinks non-null node x.
     */
    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;
    }

2、针对首尾节点的get、remove、add等操作。

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

3、contains()方法,查找某个元素在链表中的位置。没找到返回-1,否则具体的下标。

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

    public int indexOf(Object o) {
        int index = 0;
// 由于链表中是允许存放null的元素,需要判断。
        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;
    }

4、add()方法,追加在链表的末尾。不能像ArrayList那样在任意位置上追加元素。

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

5、remove()方法,核心是遍历链表,从头遍历到尾,逐个unlink()

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

6、addAll()方法,重点需要理解的方法。可分为三个步骤:
(1)找出待添加的节点及其前驱节点。换句话说,就是找到链表需要被插入的位置。
(2)把集合转换为一个子链表
(3)把子链表融入到链表里

 public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);
//将集合转换为数组,记录数组的长度,如果长度为0,说明不需要添加,则返回。
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;
//succ是待添加的节点, pred是succ的前驱节点
        Node<E> pred, succ;
//如果追加位置等于链表大小,说明是在链表的末尾位置上添加。
        if (index == size) {
            succ = null;
            pred = last;
        } else {
// node()方法详细见下文,根据下标位置得到待添加的节点和它的前驱节点。
            succ = node(index);
            pred = succ.prev;
        }
// 循环数组,把数组转换为链表的节点。
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
// 这里next为null,可能就是为null, 也可能为待添加的节点succ。
// 第一种对应在链表末尾添加,第二种对应在succ的位置上追加。
            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;
    }

7、node()方法

Node<E> node(int index) {
        // assert isElementIndex(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;
        }
    }

五、内部类
1、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源码分析

      本文链接:https://www.haomeiwen.com/subject/jrpdyctx.html