相关疑难解决方法(0)

迭代时从集合中删除元素

AFAIK有两种方法:

  1. 迭代集合的副本
  2. 使用实际集合的迭代器

例如,

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

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

是否有任何理由偏好一种方法而不是另一种方法(例如,由于可读性的简单原因,更喜欢第一种方法)?

java iteration collections

196
推荐指数
5
解决办法
22万
查看次数

标签 统计

collections ×1

iteration ×1

java ×1