Why am I not getting a java.util.ConcurrentModificationException in this example?

后端 未结 10 2267
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 07:59

Note: I am aware of the Iterator#remove() method.

In the following code sample, I don\'t understand why the List.remove in main

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 08:51

    The forward/iterator method does not work when removing items. You can remove the element without error, but you will get a runtime error when you try to access removed items. You can't use the iterator because as pushy shows it will cause a ConcurrentModificationException, so use a regular for loop instead, but step backwards through it.

    List integerList;
    integerList = new ArrayList();
    integerList.add(1);
    integerList.add(2);
    integerList.add(3);
    
    int size= integerList.size();
    
    //Item to remove
    Integer remove = Integer.valueOf(3);
    

    A solution:

    Traverse the array in reverse order if you are going to remove a list element. Simply by going backwards through the list you avoid visiting an item that has been removed, which removes the exception.

    //To remove items from the list, start from the end and go backwards through the arrayList
    //This way if we remove one from the beginning as we go through, then we will avoid getting a runtime error
    //for java.lang.IndexOutOfBoundsException or java.util.ConcurrentModificationException as when we used the iterator
    for (int i=size-1; i> -1; i--) {
        if (integerList.get(i).equals(remove) ) {
            integerList.remove(i);
        }
    }
    

提交回复
热议问题