LinkedList类源码详解

一、简介

1.继承的父类&实现的接口

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

2.底层结构

LinkedList 底层是通过 双向链表实现的。

3.基本方法

增(add)、 删(remove)、 改(set)、 查(get)

4.其他方法

1>.队列方法:

由于LinkedList 实现了 Queue(队列) 的 子接口Deque,
所以获得了以下具有 队列特征 的方法:
offer()方法:在最后面添加一个元素(入队)。
poll()方法:在最前面取走一个元素(出队)。
peek()方法:用于查看某个元素。

2>.堆栈方法:

push(E e):入栈方法
将一个元素推入到由此列表表示的堆栈中。
换句话说,将元素插入到列表的最前面成为第一个元素。
这个方法等价于{@link #addFirst}。

pop() :出栈方法
从这个列表所表示的堆栈中弹出一个元素。
换句话说,移除并返回列表的第一个元素。
这个方法等价于{@link #removeFirst()}。

5.节点类(Node)

//节点内部类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;
        }
    }

6.主要属性:

//用于记录有效元素的个数
    transient int size = 0;


/**
     * Pointer to first node.
     *
     * 第一个节点的指针。
     *
     * 1.头节点first 和 尾节点last 都为null,
     * 表示头尾两节点都没有被new过,此时链表是节点数为0的空链表。
     * 2.头节点first 没有前驱节点,但是数据域存有数据。
     *
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;
    

    /**
     * Pointer to last node.
     *
     * 指向最后一个节点的指针
     *
     * 1.头节点first 和 尾节点last 都为null,
     * 表示头尾两节点都没有被new过,此时链表是节点数为0的空链表。
     * 2.尾节点last 没有后继节点,但是数据域存有数据。
     *
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;


//序列化版本号,表示LinkedList可以被序列化和被反序列化
    private static final long serialVersionUID = 876323262645176354L;

二、主要方法

1.构造方法

1>.无参构造

/**
     * Constructs an empty list.
     *
     * 无参构造:构造一个空列表
     */
    public LinkedList() {
    }

2>.有参构造

/**
     * 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);
    }

2.增加(add)

1>.常用方法

add(E e)方法:
/**
     * Appends the specified element to the end of this list.
     *
     * 将指定的元素追加到列表的末尾。
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
add(int index, E element)方法:
/**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * 在列表的指定位置index处插入指定的元素element。
     * 将当前在该位置的元素(如果有的话)和任何后续元素向右移动(在其下标上加1)。
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        //首先检查索引index,若不满足index >= 0 && index < size,则会抛出异常。
        checkPositionIndex(index);

        //如果想要插入的索引位置index == 链表长度size
        if (index == size)
            linkLast(element);//就将元素element添加到链表的末尾
        else
            //否则,就在index对应节点node(index)之前,插入元素element。
            linkBefore(element, node(index));
    }

2>.其他方法

addFirst(E e)和 addLast(E e)方法:
/**
     * Inserts the specified element at the beginning of this list.
     *
     * 在列表的开头插入指定的元素。
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);//将 e 作为链表的第一个元素(头节点)。
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * 将指定的元素追加到列表的末尾
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * 这个方法等价于{@link #add}
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);//将 e 作为链表的最后一个元素(尾节点)。
    }
offer(E e)、offerFirst(E e)和 offerLast(E e)方法:
/**
     * Adds the specified element as the tail (last element) of this list.
     *
     * 添加指定的元素作为这个列表的尾部(最后一个元素)。
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Queue#offer})
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }

    // Deque operations
    /**
     * Inserts the specified element at the front of this list.
     *
     * 在列表的最前面插入指定的元素。
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerFirst})
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        addFirst(e);//将 e 作为链表的第一个元素(头节点)。
        return true;
    }

    /**
     * Inserts the specified element at the end of this list.
     *
     * 在列表的末尾插入指定的元素。
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerLast})
     * @since 1.6
     */
    public boolean offerLast(E e) {
        addLast(e);//将 e 作为链表的最后一个元素(尾节点)。
        return true;
    }
push(E e)方法:
/**
     * Pushes an element onto the stack represented by this list.  In other
     * words, inserts the element at the front of this list.
     *
     * <p>This method is equivalent to {@link #addFirst}.
     *
     * 将一个元素推入到由此列表表示的堆栈中。
     * 换句话说,将元素插入到列表的最前面成为第一个元素。
     * 这个方法等价于{@link #addFirst}。
     *
     * @param e the element to push
     * @since 1.6
     */
    public void push(E e) {
        addFirst(e);
    }

3.删除(remove)

1>.常用方法

remove(Object o)方法:
/**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * {@code i}
     *
     * 从列表中删除指定元素的第一个出现项(如果它存在的话)。
     * 如果该列表不包含该元素,则该元素不变。
     * 更正式地说,删除索引最低的元素{@code i}
     *
     * such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);//从链表中删除数据元素o对应的非空节点x
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);//从链表中删除数据元素o对应的非空节点x
                    return true;
                }
            }
        }
        return false;
    }
remove(int index)方法:
 /**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     *
     * 移除列表中指定位置的元素。
     * 将所有后续元素向左移动(从其下标中减去1)。
     * 返回从列表中删除的元素。
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        //首先检查索引index,若不满足index >= 0 && index < size,则会抛出异常。
        checkElementIndex(index);
        //从链表中删除 非空节点
        return unlink(node(index));
    }

2>.其他方法

remove()、removeFirst()和 removeLast() 方法:
/**
     * Retrieves and removes the head (first element) of this list.
     *
     * 检索查看并删除列表的头(第一个元素)。
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }

/**
     * 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);
    }

poll()、pollFirst()和 pollLast() 方法:
/**
     * Retrieves and removes the head (first element) of this list.
     *
     * 检索查看并删除列表的头(第一个元素)。
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

/**
     * Retrieves and removes the first element of this list,
     * or returns {@code null} if this list is empty.
     *
     * 删除列表中的第一个元素,如果列表为空则返回{@code null}。
     *
     * @return the first element of this list, or {@code null} if
     *     this list is empty
     * @since 1.6
     */
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * Retrieves and removes the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * 检索并删除列表的最后一个元素,如果列表为空,则返回{@code null}
     *
     * @return the last element of this list, or {@code null} if
     *     this list is empty
     * @since 1.6
     */
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

pop()方法:
/**
     * Pops an element from the stack represented by this list.  In other
     * words, removes and returns the first element of this list.
     *
     * <p>This method is equivalent to {@link #removeFirst()}.
     *
     * 从这个列表所表示的堆栈中弹出一个元素。换句话说,移除并返回列表的第一个元素。
     * 这个方法等价于{@link #removeFirst()}。
     *
     * @return the element at the front of this list (which is the top
     *         of the stack represented by this list)
     * @throws NoSuchElementException if this list is empty
     * @since 1.6
     */
    public E pop() {
        return removeFirst();
    }

4.修改(set)

set(int index, E element) 方法:

/**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * 将列表中指定位置index处的元素,替换为指定元素element。
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        //首先检查索引index,若不满足index >= 0 && index < size,则会抛出异常。
        checkElementIndex(index);
        //node(index)方法:返回指定索引index处的(非空)节点。
        Node<E> x = node(index);
        //保存index处数据域原来的值,并作返回处理
        E oldVal = x.item;
        //对index处节点的数据域进行值修改
        x.item = element;
        return oldVal;
    }

5.查找

1>.常用方法

get(int index) 方法:
 /**
     * Returns the element at the specified position in this list.
     *
     * 返回列表中指定位置index处的元素。
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        //首先检查索引index,若不满足index >= 0 && index < size,则会抛出异常。
        checkElementIndex(index);
        //node(index)方法:返回指定索引index处的(非空)节点。
        return node(index).item;
    }

2>.其他方法

getFirst() 和 getLast() 方法:
 /**
     * 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;
    }
peek()、peekFirst() 和 peekLast() 方法:
/**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * 检索查看列表的头(第一个元素),但不删除。
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

/**
     * Retrieves, but does not remove, the first element of this list,
     * or returns {@code null} if this list is empty.
     *
     * 检索查看但不删除列表的第一个元素,如果列表为空,则返回{@code null}。
     *
     * @return the first element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

    /**
     * Retrieves, but does not remove, the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * 检索查看但不删除列表的最后一个元素,如果列表为空,则返回{@code null}
     *
     * @return the last element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

三、底层实现

1.添加原理

1.linkFirst(E e)方法:

addFirst(E e) 的子方法。

/**
     * Links e as first element.
     * 将 e 作为链表的第一个元素(头节点)。
     */
    private void linkFirst(E e) {
        final Node<E> f = first;//用f记录当前链表的头节点
        //新节点newNode的前驱节点是当前尾节点l,后继节点为空
        final Node<E> newNode = new Node<>(null, e, f);

        //记录头节点的first指针 ,此时更新为新节点的地址引用(新添加的节点成为了头节点)
        first = newNode;
        //如果原来的头节点f为null,表示此链表是个节点个数为0的空链表
        if (f == null)
            //说明,想要添加的newNode节点是整个链表中的第一个节点
            //那么,新添加的节点不仅仅是这个链表的头节点,同时也是这个链表的尾节点。
            last = newNode;
        else
            //否则表示,此链表内的节点个数>0
            //那么,原来头节点f的上一个节点就是当前添加的新节点
            f.prev = newNode;

        size++;//节点个数+1
        modCount++;
    }

2.linkLast(E e)方法:

add(E element)、add(int index, E element)、addLast(E element) 的子方法。

/**
     * Links e as last element.
     * 将 e 作为链表的最后一个元素(尾节点)。
     */
    void linkLast(E e) {
        final Node<E> l = last;//用l记录当前链表的尾节点
        //新节点newNode的前驱节点是当前尾节点l,后继节点为空
        final Node<E> newNode = new Node<>(l, e, null);

        //记录尾节点的last指针 ,此时更新为新节点的地址引用(新添加的节点成为了尾节点)
        last = newNode;
        //如果原来的尾节点l为null,表示此链表是个节点个数为0的空链表
        if (l == null)
            //说明,想要添加的newNode节点是整个链表中的第一个节点
            //那么,新添加的节点不仅仅是这个链表的尾节点,同时也是这个链表的头节点。
            first = newNode;
        else
            //否则表示,此链表内的节点个数>0
            //那么,原来尾节点l的下一个节点就是当前添加的新节点
            l.next = newNode;
        size++;//节点个数+1
        modCount++;
    }

3.linkBefore(E e, Node succ)方法:

add(int index, E element) 的子方法。

/**
     * Inserts element e before non-null Node succ.
     * 在 非空节点succ 之前插入 元素e。
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;//pred指针 记录 目标节点succ 的上一个节点
        //新节点newNode的前驱节点是目标节点succ的上一个节点pred,后继节点是目标节点succ
        final Node<E> newNode = new Node<>(pred, e, succ);

        //目标节点succ 的上一个节点更新为 新加节点newNode
        succ.prev = newNode;
        //如果 目标节点succ 原来的前驱节点pred 为null,
        // 表示 目标节点succ就是头节点,元素e想要插到头节点succ的前面
        if (pred == null)
            //那么,待插入节点newNode就是头节点
            first = newNode;
        else

            pred.next = newNode;
        size++;
        modCount++;
    }

2.删除原理

1.unlinkFirst(Node f)方法:

/**
     * Unlinks non-null first node f.
     * 解除 第一个非空节点f 的链接。
     *
     * 头节点first指针 指向 f的下一个节点,
     * f节点 及其前面的所有节点都被丢弃。
     * 整个链在f节点处断开,f节点的下一个节点成为了first头节点。
     */
    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;//头节点指针first 直接指向目标节点f的下一个节点
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

2.unlinkLast(Node l)方法:

removeLast()、pollLast() 的子方法。

/**
     * Unlinks non-null last node l.
     * 解除 最后一个非空节点l 的链接。
     *
     * 尾节点last指针 指向 l的上一个节点,
     * l节点 及其后面的所有节点都被丢弃。
     * 整个链在l节点处断开,l节点的上一个节点成为了last尾节点。
     */
    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;//尾节点指针last 直接指向目标节点l的上一个节点
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

3.unlink(Node x)方法:

remove(Object 0)、remove(int index) 的子方法。

/**
     * Unlinks non-null node x.
     * 从链表中删除 非空节点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 {
            //当前节点x的上一个节点prev的后继节点,变成了当前节点x的下一个节点next
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            //当前节点x的下一个节点next的前驱节点,变成了当前节点x的上一个节点next
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值