LinkedList源码分析

LinkedList底层实现采用双向循环链表。LinkedList的插入与删除操作都不涉及到元素的移动,改变的只是元素的指向而已。

LinkedList的查找速度是很慢的,因为涉及到元素的逐个获取与比较。

LinkedList与ArrayList的区别,本质上是链表和数组的区别。

import java.util.LinkedList;
import java.util.List;

public class Test2 {
    public static void main(String[] args) {
        List<String> list = new LinkedList<>();
        list.add("a");
    }
}

查看LinkedList的构造方法

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

其构造方法内容为空

然后看add方法

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

查看linkLast(e)

/**
     * Links e as last element.
     */
    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++;
    }

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

这样就实现了添加一个元素。

remove方法

 /**
     * 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} 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);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
原文地址:https://www.cnblogs.com/vincent4code/p/4797692.html