拣几个重要的方法说一下:
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;
}
}