Java , Removing object from ArrayList

前端 未结 4 450
独厮守ぢ
独厮守ぢ 2021-01-16 23:02

I have ClassA which has a static ArrayList of Objects

public static ArrayList meteorits = new ArrayList();

相关标签:
4条回答
  • 2021-01-16 23:38

    When using an iterator; you need to use the iterator to remove items from a list using this:

    iterator.remove();
    

    which from the Java Docs says:

    Removes from the underlying collection the last element returned by this iterator.

    Removing a item from the list by any other means will result in the ConcurrentModificationException you are seeing.

    0 讨论(0)
  • 2021-01-16 23:38
    Iterator<Integer> itr = yourlist.iterator();
    
    // remove all even numbers
    while (itr.hasNext()) {
           itr.remove();
    }
    

    this must work for you, other way to work around this issue is to use CopyOnWriteArrayList hopefully it help.

    0 讨论(0)
  • 2021-01-16 23:46

    Basically, you need to use iterator to avoid such concurrent modification:

    List<String> list = new ArrayList<>();
    for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
        String string = iterator.next();
        if (string.isEmpty()) {
            iterator.remove();
        }
    }
    

    For more details, please check out this post:

    Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop

    0 讨论(0)
  • 2021-01-16 23:50

    It is because some thread is actually viewing this list in a for each loop, maybe you are trying to remove elements of this list in the body of for-each? You can't remove elements in for-each, but you can in iterator loops:

    You can use iterator instead of for each to remove and view the elements of the list like this:

    public static ArrayList<Meteorit> meteorits = new ArrayList<Meteorit>();
    
    Iterator<Meteorit> itr = meteorits.iterator();
    
    while (itr.hasNext()) {
           if (itr.next()==this) {
              itr.remove();
           }
    }
    
    0 讨论(0)
提交回复
热议问题