我正在开发一个包含一些遗留代码的应用程序。这里有一个链表,代码在 while 循环中使用迭代器迭代该链表。
LinkedList ll = grammarSection.getSectionsAsLinkList();
Iterator iter = ll.iterator();
int i=0;
while (iter.hasNext()) {
1. GrammarSection agrammarSection = (GrammarSection) iter.next();
2. grammarLineWithMatches = m_grammarLineMatcher.getMatch(agrammarSection, p_line);
3. if (grammarLineWithMatches != null) { //condition a
4. if (getPeek(ll)!=agrammarSection)
5. ll.addFirst(ll.remove(i)); //changing the linkedlist Line5
return grammarLineWithMatches;
}
i++;
}
在 while 循环中,如果条件 a 为真,则链表被修改为第 5 行。但是,在这种情况下,第 1 行的下一个方法会抛出 ConcurrentModificationException。如何在不获取任何 ConcurrentModificationException 的情况下添加和删除链表
最佳答案
您无法更改当前正在迭代的集合。您可以:
- 创建它的副本并迭代副本
- 不要使用迭代器 - 从 0 循环到
list.size()
。但是对于LinkedList
,这是不高效的。
如果只是关于移除,你可以使用 iter.remove()
,但你也有 addFirst(..)
关于java - 迭代链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6018295/