简体   繁体   中英

Java - Parsing ArrayList with 2 iterators and the dreaded ConcurrentModificationException

I am searching through a ArrayList and doing a compare with 2 iterators. I am writing out values to a String buffer that will eventually be a XML output. As I parse through the values I am checking for matching itemIds. The matches are normally parts and drawings. There can be many drawings to a part. For my XML I have to know the type and name of all the matches and append the values together.

Using this ArrayList:

itemId type name

1000 part hammer
1001 part nail
1000 dwg semantic
1002 part ruler

My sample XML output would roughly look like :

<Master itemId=1000 type=part name=hammer>
  <Extra type=dwg name=semantic>
</Master>
<Master itemId=1001 type=part name=nail>
</Master>
<Master itemId=1002 type=part name=ruler>
</Master>

This is my first loop

while (theBaseInterator.hasNext()){
     ImportedTableObjects next = theBaseInterator.next(); 
     currentEntry = next.identiferId;
     currentType = next.typeId;
     currentDatasetName = next.nameId;
     compareInterator = tArray.listIterator(theBaseInterator.nextIndex());
     compareEntriesofArray(currentEntry, currentType, currentDatasetName, compareInterator); <======= calling method for 2nd loop and compare check
  }

I written a method for the second loop and compare

private void compareEntriesofArray(Object currentEntry, Object currentType, Object currentDatasetName, ListIterator<ImportedTableObjects> compareInterator)
object nextEntry;   
while (compareInterator.hasNext()) {
    ImportedTableObjects next = compareInterator.next();
    nextEntry = next.identiferId;
    if(nextEntry.equals(currentEntry)) { 
    compareInterator.remove();
    }   

When it finds a match I am trying to remove the matching entry from the list. There is no need to re-check entries that has been matched. So when the 1st loop continues down the list - it does not have to check that entry again.

But of course I am getting the ConcurrentModificationException. I fully understand why. Is there a way that instead of trying to remove the entry, I can some how mark it with a boolean or something, so when the first loop gets to that entry in the list it knows to skip it and go to the next?

Add all elements you want to remove into a new List.

After iterating, call:

coll1.removeAll (coll2);

Not with iterators, and their hasNext/next, but with Lists, you can iterate with a for-loop from top to bottom. removing element (7) bevore visiting element (6) and so on has never been a problem for me, but I haven't seen it being recommended.

Here complete code

import java.util.*;

public class GuessGame 
{
    public static void main ( String [] args )
    {
        char [] ca = "This is a test!".toCharArray ();
        List <Character> ls = new ArrayList <Character> ();
        for (char c: ca)
            ls.add (c);

        show (ls);
        // first method: remove from top/end and step backwise:
        for (int i = ls.size () - 1; i >= 0; --i)
        {
            char c = ls.get (i); 
            if (c == 'i' || c == 'a' || c == 'e')
                ls.remove (i); 
        }
        show (ls);

        // second approach: collect elements to remove ...
        ls = new ArrayList <Character> ();
        for (char c: ca)
            ls.add (c);
        show (ls);
        // ... in a separate list and 
        List <Character> toRemove = new ArrayList <Character> ();
        for (char c: ls)
        {
            if (c == 'i' || c == 'a' || c == 'e')
                toRemove.add (c); 
        }
        // ... remove them all in one go:
        ls.removeAll (toRemove);
        show (ls);
    }

    private static void show (List <Character> ls)
    {
        for (char c: ls)
            System.out.print (c + " ");
        System.out.println ();
    }   
}

Output:

T h i s   i s   a   t e s t ! 
T h s   s     t s t ! 
T h i s   i s   a   t e s t ! 
T h s   s     t s t ! 

最简单的方法可能是创建另一个列表,在该列表中放置“匹配的”条目,然后对照该列表进行检查。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM