Remove elements from collection while iterating

2019-01-03 01:10发布

AFAIK, there are two approaches:

  1. Iterate over a copy of the collection
  2. Use the iterator of the actual collection

For instance,

List<Foo> fooListCopy = new ArrayList<Foo>(fooList);
for(Foo foo : fooListCopy){
    // modify actual fooList
}

and

Iterator<Foo> itr = fooList.iterator();
while(itr.hasNext()){
    // modify actual fooList using itr.remove()
}

Are there any reasons to prefer one approach over the other (e.g. preferring the first approach for the simple reason of readability)?

8条回答
甜甜的少女心
2楼-- · 2019-01-03 02:07

In Java 8, there is another approach. Collection#removeIf

eg:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

list.removeIf(i -> i > 2);
查看更多
Bombasti
3楼-- · 2019-01-03 02:07

why not this?

for( int i = 0; i < Foo.size(); i++ )
{
   if( Foo.get(i).equals( some test ) )
   {
      Foo.remove(i);
   }
}

And if it's a map, not a list, you can use keyset()

查看更多
登录 后发表回答