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

后端 未结 10 2121
佛祖请我去吃肉
佛祖请我去吃肉 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:29

    One way to handle it it to remove something from a copy of a Collection (not Collection itself), if applicable. Clone the original collection it to make a copy via a Constructor.

    This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

    For your specific case, first off, i don't think final is a way to go considering you intend to modify the list past declaration

    private static final List integerList;
    

    Also consider modifying a copy instead of the original list.

    List copy = new ArrayList(integerList);
    
    for(Integer integer : integerList) {
        if(integer.equals(remove)) {                
            copy.remove(integer);
        }
    }
    

提交回复
热议问题