我想使用链表来执行元素的提取和插入,尝试启发式的所有组合.链接列表对于此类操作更有效.因为我想尝试所有可能的提取/插入对,我在列表中使用了两个不同的迭代器.这引发了"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)
谢谢