java集合之LinkedList详解

我们上一次说到List的ArrayList,我们这次去看下LinkedList---顾名思义是链表,链表的优点就不用说了吧,增删效率比较高(具体的朋友们上网看吧),先来看下LinkedList的整体构架:

 首先我们看到了LinkedList间接的实现了List接口(说明LinkedList是有list的特性的,add,remove等)、实现了Cloneable(可复制)、Serializable(进行了序列化),除此之外还有一个东西还实现了Queue(队列,说明应该是有队列的一些特性,pop等),这次先不侧重queue的东西,我们主要看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;
    //链表维护的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;
        }
    }

我们可以看到,我们链表维护了一个size、first(头)和last(尾),我们可以看到Node的结构中有个item、next、prev充分说明了此链表是一个双向链表。

    public static void main(String[] args){
        //初始化linkedList
        List<String> linkedList = new LinkedList<>();
        //添加元素
        linkedList.add("abc");
        linkedList.add("bcd");
        return;
    }

这个空的构造函数没有什么内容,所以我们就跳过去,我们直接看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})
     */
    //看方法注释,我们可以看到是将该元素添加到此链表的end,返回true
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    /**
     * Links e as last element.
     */
    void linkLast(E e) {

        //首先取出last节点
        final Node<E> l = last;

        //将newNode的prev指向last,后节点指向null,因为newNode永远都是作为last的,所以next指向null
        final Node<E> newNode = new Node<>(l, e, null);

        //last指向newNode
        last = newNode;

        //如果链表为null的话则first也指向newNode,此时链表只有一个节点first和last都指向一个
        //如果链表部位null,只需要将last的next指向这个newNode就行了,这样就形成了双向链表
        if (l == null)
            first = newNode;
        else
            l.next = newNode;

        //最后size++
        size++;
        modCount++;
    }

LinkedList就是这样一个节点一个节点关联起来的,我们可以看一下下面的图片(这里偷个懒,网上随便找了一张):

 我们接下来看一下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) {
        //检查index是否超出范围size
        checkElementIndex(index);
        //删除指定位置的节点,首先得找到这个节点
        return unlink(node(index));
    }
    //检查index是否正确
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    //返回指定index位置的节点
    Node<E> node(int index) {
        // assert isElementIndex(index);
        
        //首先去比较index和size >> 1(也就是size的一半),如果比中间数小则从链表头找,否则从尾找
        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;
        }
    }

我们可以看到,我们想要移除指定位置的节点,首先得找到这个节点(这个是重点),关键我们的链表如何找到指定位置?不知道大家有没有自己比较好的方法,我们来看下jdk的思路(我觉得jdk的实现方法很有趣),node(int index)方法中的if条件拿index和size的一半比较,文字解释太麻烦了,我来画个图吧:

假设:我们linkedList的长度为6,如要remove的index为3,此时我们3 < (size >> 1)为false,则我们从linkedList后面开始直到变量i>index,此时i变量位置的就是index位置的node,如果我们index是2,那么是从前面开始的,我们大家想这样其实是把linkedList从中间分为2个,速度是不是比没分之前快两倍呢,哈哈哈~

总结:linkedList为双链表,维护的是一个first和last指针,而每个节点有item自身、prev和next两个节点来维护双链表的关系,其他的功能都是围绕我们的双链表来进行的,有兴趣的大家可以仔细研究一下源码,有时会发现很有趣的小细节哦~

  • 21
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值