如何在Java中的链接列表中使用两个不同的迭代器?

Dav*_*der 5 java iterator heuristics linked-list concurrentmodification

我想使用链表来执行元素的提取和插入,尝试启发式的所有组合.链接列表对于此类操作更有效.因为我想尝试所有可能的提取/插入对,我在列表中使用了两个不同的迭代器.这引发了"ConcurrentModificationException".如何在不重新遍历列表的情况下有效地执行此操作,因为这会破坏首先使用列表的整个目的?

以下是代码的相关部分:

ListIterator<Integer> it1 = data.listIterator();
ListIterator<Integer> it2;

while(it1.hasNext()) {
    int i = it1.next();
    it2 = data.listIterator();

    while(it2.hasNext()) {
        if (i == it2.next()) continue; // continue right away when the indexes are equal
        it1.remove();
        it2.add(i);
        if (length() < best)
            return true;
        }

    // when the swap is not better/consistent
    it2.remove();
    it1.add(i);
}
return false;
Run Code Online (Sandbox Code Playgroud)

谢谢

mur*_*uga 0

当您仅执行读取操作时,可以在 LIST 上使用任意数量的迭代器。由于您正在此处执行删除/添加操作,因此您不能将同一个列表与两个不同的迭代器一起使用,因为这会导致您现在遇到的 ConcurrentModificationException 异常。

你想实现什么目标?也许,人们可以帮助您提供不同的选择。