Iterate a linked list

I am working on an application that has some inherited code. There is a linked list here, and the code iterates over this list of links using an iterator in the while loop.

        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++;
        }

In a while loop, if condition a is true, then the linked list changes as in line 5. However, in this case, the next method on line1 throws a ConcurrentModificationException. How to add and remove linked list without getting ConcurrentModificationException

+3
source share
3 answers

Short answer: you cannot.

JDK List , ( , , ).

LinkedList. , , . .

+1

, . :

  • iterator-loop 0 list.size(). LinkedList .

, iter.remove(), addFirst(..)

+2

- , ConcurrentModificationException.

:

instead of removing items from the list during iteration, add those that will be removed to the new list, and after the loop, you can remove everything using the removeAll list method.

or vice versa, save the ones you need to save and assign the new list to the old one

+1
source

All Articles