迭代链表

我正在开发一个具有一些遗留代码的应用程序。 这里有一个链表,代码使用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行进行修改。 但是,在这种情况下,line1上的下一个方法抛出ConcurrentModificationException。 如何在不获取任何ConcurrentModificationException的情况下添加和删除链接列表

简短的回答是:你做不到。

JDK的List实现被设计为由迭代器修改,以保持迭代的顺序(没有办法判断任意列表更改是否会这样做,因此迭代器假设最坏)。

在您的情况下,解决方案是创建一个新的LinkedList 。 在迭代时,要么将迭代元素添加到新列表的结尾或开头。 然后扔掉旧的。

您无法更改当前正在迭代的集合。 您可以:

  • 创建它的副本并重复迭代副本
  • 不要使用迭代器 – 从0循环到list.size() 。 但是使用LinkedList效率不高。

如果它只是删除,你可以使用iter.remove() ,但你也有addFirst(..)

迭代器是快速失败的迭代器,因此它可能会抛出ConcurrentModificationException。

最简单的解决方案是;

而不是在迭代时从列表中删除项目,将要删除的项目添加到新列表中,在循环之后,您可以使用removeAll方法列表删除所有这些项目。

反之亦然,保留您需要保留的那些并将新列表分配给旧列表