20

我的 android 应用程序中有以下代码:

/**
 * callback executed after fetching the data.
 */
public void OnPointsFetch(ArrayList<Shop> result) {

    toggleLoader(false);

    this.shops = result;

    if(activeFilter == Constants.POINTS_FILTER_AVAILABLE){
        for(Shop s : result){
            if(s.getClientPoints().getPointsAvailable() == 0){
                this.shops.remove(s);
            }
        }
    }
    else{
        for(Shop s : result){
            if(s.getClientPoints().getPointsSpent() == 0){
                this.shops.remove(s);
            }   
        }
    }


    ptsListAdapter.setCollection(this.shops);
    ptsListAdapter.setFilter(this.activeFilter);

}

在异步任务的结果上调用此方法。在传递给列表适配器之前,我需要删除集合的一些元素。

    11-23 17:39:59.760: E/AndroidRuntime(19777): java.util.ConcurrentModificationException
11-23 17:39:59.760: E/AndroidRuntime(19777):    at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
4

3 回答 3

55

在迭代列表时,您不能从列表中删除项目。您需要使用迭代器及其 remove 方法:

for(Iterator<Shop> it = result.iterator(); it.hasNext();) {
    Shop s = it.next();
    if(s.getClientPoints().getPointsSpent() == 0) {
        it.remove();
    }   
}
于 2012-11-23T17:48:06.483 回答
2

您通常会在以下情况下收到此错误

  1. 在对集合进行迭代时直接修改集合

    甚至更糟的时候

  2. 一个线程修改集合,而另一个线程对其进行迭代。

于 2012-11-23T17:50:13.877 回答
1

Not sure if the accepted answer would work, as internally it would be trying to again modify the same list. A cleaner approach would be to maintain a 'deletion' list, and keep adding elements to that list within the loop. Once we are ready with the deletion list, they can be removed after the loop. This should work in all cases where we do not need the deleted element to be reprocessed. If yes, then the existing deletion list can be checked for presence of that element.

    List<String> list = new ArrayList<String>();
    List<String> listRemove = new ArrayList<String>();

    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");
    list.add("6");
    list.add("7");
    list.add("8");

    System.out.println("list : " + list);

    for (String i : list) {
        if (i.equals("2")) {
            listRemove.add(i);
        }
    }
    list.removeAll(listRemove);
    System.out.println("updated list: " + list);
于 2014-10-20T11:30:27.953 回答