Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating a linkedlist

Tags:

java

I am working on an application which has some legacy code. Here, there is a linkedlist and the code iterates that linklist using an iterator in a 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 the while loop, if condition a is true, then the linkedlist is modified as in line5. However, in this case, the next method on line1 throws a ConcurrentModificationException. How to add and delete the linkedlist without getting any ConcurrentModificationException

like image 665
user496934 Avatar asked Oct 28 '25 12:10

user496934


2 Answers

You can't change the collection you are currently iterating. You can:

  • create a copy of it and iterate the copy instead
  • don't use iterator - loop from 0 to list.size(). But with LinkedList this is not efficient.

If it was only about removal, you can use iter.remove(), but you also have addFirst(..)

like image 80
Bozho Avatar answered Oct 30 '25 02:10

Bozho


The short answer is: you can't.

The JDK's List implementations are designed to be modified by the iterator, to preserve order of iteration (there's no way to tell whether an arbitrary list change will do this, so the iterator assumes the worst).

The solution, in your case, is to create a new LinkedList. As you iterate through, either add the iterated elements to the end or beginning of the new list. Then throw away the old.

like image 44
Anon Avatar answered Oct 30 '25 02:10

Anon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!