LinkedList源码阅读

拣几个重要的方法说一下:

1. 首先是:addAll(int index, Collection<? extends E> c)方法,将给定集合中的所有元素添加到制定的下标处

/**
 * Inserts all of the elements in the specified collection into this
 * list, starting at the specified position.  Shifts the element
 * currently at that position (if any) and any subsequent elements to
 * the right (increases their indices).  The new elements will appear
 * in the list in the order that they are returned by the
 * specified collection's iterator.
 *
 * @param index index at which to insert the first element
 *              from the specified collection
 * @param c collection containing elements to be added to this list
 * @return {@code true} if this list changed as a result of the call
 * @throws IndexOutOfBoundsException {@inheritDoc}
 * @throws NullPointerException if the specified collection is null
 */
public boolean addAll(int index, Collection<? extends E> c) {
    checkPositionIndex(index);

    //这句没看懂为什么不用c.size()
    //后面对数组遍历时也是用的foreach方式,效率也并不比直接遍历集合高
    Object[] a = c.toArray();
    int numNew = a.length;
    if (numNew == 0)
        return false;

    Node<E> pred, succ;
    if (index == size) {
        succ = null;
        pred = last;
    } else {
        succ = node(index);
        pred = succ.prev;
    }

    //这个循环是关键,当添加一个新节点时,只需要修复新节点与前驱节点的引用关系,
    //而与后继节点的引用关系在下一次遍历时会修复,而且由于当前并不知道后继节点是谁,
    //所以也不可能修复与后继节点的关系。
    for (Object o : a) {
        @SuppressWarnings("unchecked") E e = (E) o;
        Node<E> newNode = new Node<>(pred, e, null);
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        pred = newNode;
    }

    if (succ == null) {
        last = pred;
    } else {
        pred.next = succ;
        succ.prev = pred;
    }

    size += numNew;
    modCount++;
    return true;
}

插入一个集合还有一种更为简单的方式,即首先找到index对应的节点(通过node(index)方法),然后循环调用

linkBefore(E e, Node<E> succ) 方法,但是这种方法的效率比较低,原因就是每调用一次linkBefore(E e, Node<E> succ)方法,实际上要修复新节点与前驱节点和后继节点的引用关系,计算量是源码中所用方法的两倍!

2. Node<E> node(int index) 方法,

  该方法找到指定下标的元素。方法会对index进行判断,如果在链表的前半部分,那么从头结点开始遍历,如果在链表的后半部分,那么从尾节点开始遍历,这样确保遍历的此时小于size的一半。值得一提的是,求size的一半不是直接除2,而是采用移位运算,将size右移1,这个操作在size为正数时等价于除2。(>>右移,>>>无符号右移,忽略符号位。)

/**
 * Returns the (non-null) Node at the specified element index.
 */
Node<E> node(int index) {
    // assert isElementIndex(index);

    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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值