![](/img/trans.png)
[英]java.util.ConcurrentModificationException when removing elements from arraylist even with iterators
[英]Java - Parsing ArrayList with 2 iterators and the dreaded ConcurrentModificationException
我正在搜索ArrayList并与2个迭代器进行比较。 我正在将值写到String缓冲区,该缓冲区最终将是XML输出。 当我解析这些值时,我正在检查匹配的itemIds。 火柴通常是零件和图纸。 一个零件可以有很多图纸。 对于我的XML,我必须知道所有匹配项的类型和名称,并将值附加在一起。
使用此ArrayList:
itemId类型名称
1000零件锤
1001部分指甲
1000 dwg语义
1002尺子
我的样本XML输出大致如下所示:
<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>
这是我的第一个循环
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
}
我为第二个循环编写了一个方法并进行比较
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();
}
当找到匹配项时,我正尝试从列表中删除匹配项。 无需重新检查已匹配的条目。 因此,当第一个循环继续在列表中向下移动时-不必再次检查该条目。
但是当然我得到了ConcurrentModificationException。 我完全理解为什么。 有没有一种方法可以代替尝试删除该条目,而是可以用布尔值或其他方式标记它,因此当第一个循环到达列表中的该条目时,它知道将其跳过并转到下一个?
将要删除的所有元素添加到新列表中。
迭代后,调用:
coll1.removeAll (coll2);
不是使用迭代器及其hasNext / next,而是使用列表,您可以从上到下使用for循环进行迭代。 删除元素(7)之前访问元素(6)等等对我来说从来都不是问题,但我还没有看到有人推荐它。
这里完整的代码
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 ();
}
}
输出:
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 !
最简单的方法可能是创建另一个列表,在该列表中放置“匹配的”条目,然后对照该列表进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.