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

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

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

    List files = Arrays.asList(dir.listFiles());
    
    Iterator i = files.iterator();
    
    while (i.hasNext()) {
        File file = i.next();
        if (!file.getName().endsWith(".xml")) {
            i.remove();
        }
    }
    

提交回复
热议问题