我期待在 Java 的 LinkedList 中找到它,因为链表的目的是能够在任何地方有效地插入(和删除)(假设您有某种指向要插入或删除的位置的指针)。我在 API 中没有找到任何东西。我忽略了什么吗?
我能找到的最接近的是 ListIterator 中的 add 和 remove 方法。不过,这有一些限制。特别是,根据 API,一旦底层的 LinkedList 通过 remove 被修改,其他迭代器就会变得无效。这也出现在我的测试中;以下程序导致 IllegalStateException:
import java.util.*;
public class RemoveFromLinkedList {
public static void main(String[] args) {
LinkedList<Integer> myList= new LinkedList<Integer>();
for (int i = 0; i < 10; ++i) {
myList.add(i);
}
ListIterator<Integer> i1 = myList.listIterator();
ListIterator<Integer> i2 = myList.listIterator();
for (int i = 0; i < 3; ++i) {
i1.next();
i2.next();
}
System.out.println("i1.next() should be 3: " + i1.next());
i1.remove();
i1.remove();
// Exception!
System.out.println("i2.next() should be 5: " + i2.next());
}
}
理想情况下,我期待的是这样的:
// In my imagination only. This is the way Java actually works, afaict.
// Construct two insertion/deletion points in LinkedList myLinkedList.
myIterator = myLinkedList.iterator();
for (...) {
myIterator.next();
}
start = myIterator.clone();
for (...) {
myIterator.next();
}
// Later...
after = myLinkedList.spliceAfter(myIterator, someOtherLinkedList);
// start, myIterator, and after are still all valid; thus, I can do this:
// Removes everything I just spliced in, as well as some other stuff before that.
myLinkedList.remove(start, after);
// Now, myIterator is invalid, but not start, nor after.
C++ 的列表类(模板)有类似的东西。只有指向移动元素的迭代器才会失效,而不是所有的迭代器。