Reputation: 29
The following method throws a ConcurrentModificationException
:
Method 1 (With exception):
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);
}
And when I changed the above method to this:
Method 2 (Without exception):
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);
}
Then there's no exception! Cannot figure out why?
Exception trace:
Exception: java.util.ConcurrentModificationException java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
Complete Class:
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);
}
}
Now when getListData is called exceptions occurs.
Upvotes: 2
Views: 128
Reputation: 3795
Since sort()
methos jumble up whole collection , you have to call sort()
method first. After that call iterator()
.
Upvotes: 3