Collections removeAll method

前端 未结 5 620

I would like to know if something like below is possible,

list.removeAll(namesToRemove)

I hope the context is understandable.

The

5条回答
  •  时光取名叫无心
    2021-01-07 10:09

    Another approach: Subclass ArrayList and implement a custom method like:

    public class MyArrayList extends ArrayList {
    
       // all needed constructors
    
       public void removeAllWithNames(Collection names) {
         // following code is based on aioobe's answer
         Iterator iter = iterator();
           while (iter.hasNext())
             if (names.contains(iter.next().toString()))
               iter.remove();
       }
    }
    

    EDIT changed the code - the comment was good, now the custom list is a 'List' again, but now we use the toString() method (for simplicity) for filtering. (using a getName() method is possible but requires more lines of code)

提交回复
热议问题