以下方法引发ConcurrentModificationException
:
方法1(例外):
public List getData(int n)
{
List l = new ArrayList(statement.values());
Iterator i = l.iterator();
Calculation calculation = null;
while (i.hasNext())
{
calculation = (Calculation)i.next();
if (!calculation.total.hasScores())
i.remove();
}
Collections.sort(l);
int size = l.size();
return l.subList(0,size > n? n : size);
}
当我将上述方法更改为:
方法2(无例外):
public List getData(int n)
{
List l = new ArrayList(statement.values());
Iterator i = l.iterator();
Collections.sort(l);
Calculation calculation = null;
while (i.hasNext())
{
calculation = (Calculation)i.next();
if (!calculation.total.hasScores())
i.remove();
}
int size = l.size();
return l.subList(0,size > n? n : size);
}
那也不例外!不知道为什么?
异常跟踪:
Exception: java.util.ConcurrentModificationException java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
完成课程:
public class MyData
{
private Map <Integer, Calculation> statements = new HashMap<Integer, Calculation>();
public List getListData()
{
List listData = this.getData(5);
return listData;
}
public List getData(int n)
{
List l = new ArrayList(statement.values());
Iterator i = l.iterator();
Calculation calculation = null;
while (i.hasNext())
{
calculation = (Calculation)i.next();
if (!calculation.total.hasScores())
i.remove();
}
Collections.sort(l);
int size = l.size();
return l.subList(0,size > n? n : size);
}
}
现在,调用getListData时会发生异常。
最佳答案
由于sort()
方法混杂了整个集合,因此必须首先调用sort()
方法。之后,调用iterator()
。
关于java - 无法找出ConcurrentModificationException的原因,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32883602/