Java: How to remove elements from a list while iterating over/adding to it

后端 未结 9 1922
谎友^
谎友^ 2020-12-10 11:38

This question is a more special case of the problem described (and solved) in this question.

I have two methods, stopAndRemove(ServerObject server) and a close() met

9条回答
  •  爱一瞬间的悲伤
    2020-12-10 12:18

    Perhaps this is the wrong way to do it, but I always create a removal collection, which contains indexes or references to the objects that need to be removed. I then iterate over that collection and remove those indexes/objects from the original collection. Probably not the most efficient but it got the job done.

    Instead of

    for(Collection things : thing)  
        things.remove(thing)
    

    I use

    Collection toRemove = new LinkedList();
    for(things : thing)
        toRemove.add(thing);
    
    for(toRemove : thing)
        things.remove(thing)
    

提交回复
热议问题