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

后端 未结 9 1841
谎友^
谎友^ 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:07

    When I've done this before, I always used the "old school" LinkedList collection, an Iterator, and the Iterator.remove() method to remove the current item.

    0 讨论(0)
  • 2020-12-10 12:07

    Refactor out all the ServerObject stopping code from stopAndRemove into a private stopServer method, and then do the removal separately in stopAndRemove and closeCurrentlyOpen. Then you can use a ListIterator to remove them (or just stop them all in a for loop and clear the list at the end).

    0 讨论(0)
  • 2020-12-10 12:10

    ... removing files that aren't XML from a directory list...

    List<File> files = Arrays.asList(dir.listFiles());
    
    Iterator<File> i = files.iterator();
    
    while (i.hasNext()) {
        File file = i.next();
        if (!file.getName().endsWith(".xml")) {
            i.remove();
        }
    }
    
    0 讨论(0)
  • 2020-12-10 12:13

    Split off a method stop() from stopAndRemove(). Then write the loop with an explicit iterator, do the stop and then iterator.remove().

    "and" in a method name is a code smell.

    0 讨论(0)
  • Similar to firebird84. But u can use removeAll(Collection c) api

    for(String exitingPermission : existingPermissions){                
        //remove all permissions for the screen and add the new ones
        if(exitingPermission.split("_")[0].equals(screen)){
            removePermissions.add(exitingPermission);
        }
     }
    existingPermissions.removeAll(removePermissions);
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题