LinkedListにおけるaddAll(int index,Collection extends E>c)関数解析

1063 ワード


 public boolean addAll(int index, Collection<? extends E> c) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew==0)
            return false;
	modCount++;

        Entry<E> successor = (index==size ? header : entry(index));
        Entry<E> predecessor = successor.previous;
	for (int i=0; i<numNew; i++) {
            Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
            predecessor.next = e;
            predecessor = e;
        }
        successor.previous = predecessor;

        size += numNew;
        return true;
    }

この関数も無敵で、肝心なのはcollection挿入時に秩序を保っていることで、主にそのfor循環体の中で、後続の要素はすべて前に挿入された要素の後に挿入されているので、秩序を保つことができます.