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:
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
Output: