java.util.ConcurrentModificationException android after remove elements from array list

前端 未结 3 1564
别跟我提以往
别跟我提以往 2021-02-12 21:47

I have the folloing code in my android app:

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

             


        
相关标签:
3条回答
  • 2021-02-12 22:01

    You can't remove items from a list while iterating over it. You need to use an iterator and its remove method:

    for(Iterator<Shop> it = result.iterator(); it.hasNext();) {
        Shop s = it.next();
        if(s.getClientPoints().getPointsSpent() == 0) {
            it.remove();
        }   
    }
    
    0 讨论(0)
  • 2021-02-12 22:02

    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);
    
    0 讨论(0)
  • 2021-02-12 22:13

    You get this error typically when

    1. You modify the collection directly while it is iterating over the collection

      or even worse when

    2. one threads modifies the collection, while another iterates over it.

    0 讨论(0)
提交回复
热议问题