无法找出ConcurrentModificationException的原因

时间:2015-10-01 09:07:44

标签: java exception

以下方法抛出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时会发生异常。

1 个答案:

答案 0 :(得分:3)

由于sort()方法混杂了整个集合,您必须先调用sort()方法。之后致电iterator()