LinkedList源码阅读(JDK 8)

LinkedList源码阅读,归纳了下面三个点:
1.内部静态类

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

Node类整个LinkedList的核心数据结构
双向列表,结构简单
左指针|值|右指针

2.LinkedList成员属性

    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; 

LinkedList主要的成员属性
size:和ArrayList一样,size为插入的元素的大小,一些方法如:size(),isEmpty()均按这个属性判断进行返回
first和last是链表的首指针尾指针,分布指向链表的首部和尾部,first和last指向同一内存块,但指向的顺序不同。

3.重要方法:
add(E e) ;
add(int index, 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;
    }
    /**
     * 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 first element.
     * 在第一个位置插入数据到链表
     */
    private void linkFirst(E e) {
        final Node<E> f = first;

        /** 
         * new 对象的时候,实际上已经指派了指针
         * 因为是插入第一个元素,所以first要指派在右指针
         */
        final Node<E> newNode = new Node<>(null, e, f);


        first = newNode;
        if (f == null)
            last = newNode;
        else
            //原来的元素指派左指针到新的元素
            f.prev = newNode;
        size++;
        modCount++;
    }

    /**
     * Links e as last element.
     * 在最后一个位置插入数据到链表
     */
    void linkLast(E e) {
        final Node<E> l = last;

        /** 
         * new 对象的时候,实际上已经指派了指针
         * 因为是插入最后一个元素,所以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.
     * 在某个节点(我们把这个节点叫SUCC节点)前插入数据
     * 
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        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++;
    }

linkFirst方法为例子,改链表的插入过程类似于下图:
这里写图片描述
可以归纳:链表的新增过程无非1.创建对象。2.指派指针。

remove(E e) ;
remove(int index,E e) ;
与add方法相反,remove方法也是由三个对链表的操作构成。

    /**
     * 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;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            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) {
            //如果左指针为空,那么last需要指向右节点
            first = next;
        } else {
            //原对象的右指针改为原对象的前一个对象指向
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            //如果右指针为空,那么last需要指向左节点
            last = prev;
        } else {
            //原对象的左指针改为原对象的后一个对象指向
            next.prev = prev;
            x.next = null;
        }
        //对象置空,由GC回收
        x.item = null;
        size--;
        modCount++;
        return element;
    }

删除的逻辑代码比新增的要简单,且个人感觉比ArrayList写得要优雅

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;
    }
    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
        // 如果索引值大于size / 2,那么从first开始遍历获取值
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            // 如果索引值小于size / 2,那么从last开始遍历获取值
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

LinkedList的get方法体现了双向链表的优势,离那边近,则从那边开始遍历。

~~~意义
1.为什么选择LinkedList?
很古老的原因:链表利于新增和删除操作,但不利于查询。这是数据结构上顺序表和链表的区别的一种选择。(和前面的ArrayList相反)

2.LinkedList性能优化:
和ArrayList一样,先看看其构造函数:

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

LinkedList只有两个构造函数,不像ArrayList一样多了一个指定数组的构造方法。因为链表和数组不同,数组如果在初始化的时候长度指定的恰当,则可能节省空间,而链表不需要指定,本身可以实现自动增长。
3.LinkedList的成员变量都是用transient修饰,因此是非线程安全的。所以在多线程下需要慎重使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值