源码剖析集合类——LinkedList

此博客用于个人学习,来源于书籍和网上,对知识点进行一个整理。

List 集合的典型实现——LinkedList 类:

这是一个由链表构成的类。链表是一种常见的基础数据结构,是一种线性表,但是它并不会按线性的顺序存储数据,而是在每一个字节里存储到下一个节点的指针。使用链表结构可以克服数组需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取数据的有点,同时链表由于增加了节点的指针域,空间开销较大。

1. 字段属性:
//链表元素(节点)的个数
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;

这里出现了一个 Node 类,是 LinkedList 类中的一个内部类,每一个元素代表一个 Node 对象,LinkedList 就是由许多个 Node 对象类似于手拉手构成

/**
 * 内部节点类
 * @param <E>
 */
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;
    }
}
2. 构造函数:

LinkedList 有两个构造函数,第一个是默认的空的构造函数,第二个是将已有元素的集合 Collection 的实例添加到 LinkedList 中,调用的是 addAll() 方法

/**
 * 空构造函数
 *
 * Constructs an empty list.
 */
public LinkedList() {
}

/**
 * 将已有元素的集合Collection的实例添加到LinkedList中,调用的是addAll()方法
 *
 * 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);
}
3. 添加元素:

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

/**
 * Links e as first element.
 */
private void linkFirst(E e) {
    //将头节点赋值给f
    final Node<E> f = first;
    //将指定元素构造成一个新节点,此节点指向下一个节点的引用为头节点
    final Node<E> newNode = new Node<>(null, e, f);
    //将此新节点设为头节点,那么原先的头节点f变为第二个节点
    first = newNode;
    //如果第二个节点为空,也就是原先链表为空
    if (f == null)
        //将这个新节点也设为尾节点(前面已经设为头节点了)
        last = newNode;
    else
        //将原先的头节点的上一个节点指向新节点
        f.prev = newNode;
    //节点数加1
    size++;
    //和ArrayList中一样,iterator和listIterator方法返回的迭代器和列表迭代器实现使用
    modCount++;
}

2)addLast(E e) 和 add(E 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);
}

/**
 * Links e as last element.
 */
void linkLast(E e) {
    //将l设为尾节点
    final Node<E> l = last;
    //构造一个新节点,节点上一个节点引用指向为尾节点l
    final Node<E> newNode = new Node<>(l, e, null);
    //将尾节点设为创建的新节点
    last = newNode;
    //如果尾节点为空,表示原先链表为空
    if (l == null)
        //将头节点设为新创建的节点(尾节点也是新创建的节点)
        first = newNode;
    else
        //将原来尾节点下一个节点的引用指向新节点
        l.next = newNode;
    //节点数加1
    size++;
    //和ArrayList中一样,iterator和listIterator方法返回的迭代器和列表迭代器实现使用
    modCount++;
}

3)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).
 *
 * @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) {
    //判读索引是否合法,不合法抛出异常
    checkPositionIndex(index);
    //如果索引值等于链表大小
    if (index == size)
        //将节点插入尾节点
        linkLast(element);
    else
        linkBefore(element, node(index));
}

/**
 * Links e as last element.
 */
void linkLast(E e) {
    //将l设为尾节点
    final Node<E> l = last;
    //构造一个新节点,节点上一个节点引用指向为尾节点l
    final Node<E> newNode = new Node<>(l, e, null);
    //将尾节点设为创建的新节点
    last = newNode;
    //如果尾节点为空,表示原先链表为空
    if (l == null)
        //将头节点设为新创建的节点(尾节点也是新创建的节点)
        first = newNode;
    else
        //将原来尾节点下一个节点的引用指向新节点
        l.next = newNode;
    //节点数加1
    size++;
    //和ArrayList中一样,iterator和listIterator方法返回的迭代器和列表迭代器实现使用
    modCount++;
}

/**
 * Inserts element e before non-null Node succ.
 */
void linkBefore(E e, Node<E> succ) {
    // assert succ != null;
    //将pred设为插入节点的上一个节点
    final Node<E> pred = succ.prev;
    //将新节点的上引用设为pred,下引用设为succ
    final Node<E> newNode = new Node<>(pred, e, succ);
    //succ的上一个节点的引用设为新节点
    succ.prev = newNode;
    //如果插入节点的上一个节点引用为空
    if (pred == null)
        //新节点就是头节点
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}
4. 删除元素:

删除元素和添加元素一样,也是通过更改指向上一个节点和指向下一个节点的引用

1)remove() 和 removeFirst():

该命令为从此列表中移除并返回第一个元素

/**
 * 从此列表中移除并返回第一个元素
 *
 * 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);
}

/**
 * Unlinks non-null first node f.
 */
private E unlinkFirst(Node<E> f) {
    // assert f == first && f != null;
    final E element = f.item;
    //next为头节点的下一个节点
    final Node<E> next = f.next;
    //将节点的元素和引用都设为null,便于垃圾回收
    f.item = null;
    f.next = null; // help GC
    //修改头节点为第二个节点
    first = next;
    //如果第二个节点为空(当前链表只存在第一个元素)
    if (next == null)
        //那么尾节点也设置为null
        last = null;
    else
        //如果第二个节点不为空,那么将第二个节点的上一个引用设置为null
        next.prev = null;
    size--;
    modCount++;
    return element;
}

2)removeLast():

该命令为从该列表中删除并返回最后一个元素

/**
 * 从该列表中删除最后一个元素
 *
 * 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);
}

/**
 * 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;
    //将节点的值和引用都设为null,便于垃圾回收
    l.item = null;
    l.prev = null; // help GC
    //尾节点为倒数第二个节点
    last = prev;
    //如果倒数第二个节点为null
    if (prev == null)
        //那么将节点也设置为null
        first = null;
    else
        //如果倒数第二个节点不为空,那么将倒数第二个节点的下一个引用设置为null
        prev.next = null;
    size--;
    modCount++;
    return element;
}

3)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.
 *
 * @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) {
    //判断索引是否合法,不合法抛出异常
    checkElementIndex(index);
    return unlink(node(index));
}

/**
 * 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;
    //如果删除节点位置的上一个节点引用为null(表示删除第一个元素)
    if (prev == null) {
        //将头节点设置为第一个元素的下一个节点
        first = next;
        //如果删除节点位置的上一个节点引用不为null
    } else {
        //将删除节点的上一个节点的引用指向删除节点的下一个节点(去掉删除节点)
        prev.next = next;
        //删除节点的上一个节点引用设置为null
        x.prev = null;
    }
    //如果删除节点的下一个节点引用为null(表示删除最后一个节点)
    if (next == null) {
        //将尾节点设置为删除节点的上一个节点
        last = prev;
        //不是删除尾节点
    } else {
        //将删除节点的下一个节点的上一个节点的引用指向删除节点的上一个节点
        next.prev = prev;
        //将删除节点的下一个节点引用设置为null
        x.next = null;
    }
    //删除节点内容设置为null,便于垃圾回收
    x.item = null;
    size--;
    modCount++;
    return element;
}

4)remove(Object o):

此方法和 remove(int index) 没有多大差别,都是删除第一次出现的指定元素,但这个是通过循环判断元素进行删除

/**
 * 删除第一次出现的元素
 *
 * Removes the first occurrence of the specified element from this list,
 * if it is present.  If the list does not contain the element, it is
 * unchanged.  More formally, removes the element with the lowest index
 * <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 * (if such an element exists).  Returns <tt>true</tt> 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 <tt>true</tt> if this list contained the specified element
 */
public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}
5. 修改元素:

通过调用 set(int index,E element) 方法,用指定的元素替换此列表中指定位置的元素

/**
 * 用指定的元素替换此列表中指定位置的元素
 *
 * Replaces the element at the specified position in this list with the
 * specified 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) {
    //判断索引是否合法,不合法则抛出异常
    checkElementIndex(index);
    //获取指定索引处的元素
    Node<E> x = node(index);
    E oldVal = x.item;
    //将指定位置的元素替换成要修改的元素
    x.item = element;
    //返回指定索引位置原来的元素
    return oldVal;
}
6. 查找元素:

1)getFirst():

该命令为返回列表中的第一个元素

/**
 * 返回此列表中的第一个元素
 *
 * 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;
}

2)getLast():

该命令为返回此列表中的最后一个元素

/**
 * 返回此列表中的最后一个元素
 *
 * 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;
}

3)get(int index):

该命令为返回指定索引处的元素

/**
 * 返回指定索引处的元素
 *
 * Returns the element at the specified position in this list.
 *
 * @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) {
    checkElementIndex(index);
    return node(index).item;
}

4)indexOf(Object o):

该命令为返回此列表中指定元素第一次出现的索引,如果此列表中不包含元素,则返回-1

/**
 * 返回此列表中指定元素第一次出现的索引,如果此列表不包含元素,则返回-1
 *
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index {@code i} such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 * or -1 if there is no such index.
 *
 * @param o element to search for
 * @return the index of the first occurrence of the specified element in
 *         this list, or -1 if this list does not contain the element
 */
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;
}
7. 迭代器:

在 LinkedList 集合中的也有一个内部类 ListItr,方法实现大体相似,通过移动游标指向每一次要遍历的元素,不用再遍历某个元素之前都从头开始

/**
 * Returns a list-iterator of the elements in this list (in proper
 * sequence), starting at the specified position in the list.
 * Obeys the general contract of {@code List.listIterator(int)}.<p>
 *
 * The list-iterator is <i>fail-fast</i>: if the list is structurally
 * modified at any time after the Iterator is created, in any way except
 * through the list-iterator's own {@code remove} or {@code add}
 * methods, the list-iterator will throw a
 * {@code ConcurrentModificationException}.  Thus, in the face of
 * concurrent modification, the iterator fails quickly and cleanly, rather
 * than risking arbitrary, non-deterministic behavior at an undetermined
 * time in the future.
 *
 * @param index index of the first element to be returned from the
 *              list-iterator (by a call to {@code next})
 * @return a ListIterator of the elements in this list (in proper
 *         sequence), starting at the specified position in the list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 * @see List#listIterator(int)
 */
public ListIterator<E> listIterator(int index) {
    checkPositionIndex(index);
    return new ListItr(index);
}

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

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

这里需要注意的是 modCount 字段,前面在增加和删除元素的时候,都会进行自增操作 modCount,这是因为如果一边迭代,一边用集合自带的方法进行删除或者新增操作时,都会抛出异常(使用迭代器的增删方法不会抛出异常)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值