【问题标题】:Removing item from list while iterating迭代时从列表中删除项目
【发布时间】:2014-10-26 03:50:36
【问题描述】:

在遍历列表时,可能会删除一个项目。

private void removeMethod(Object remObj){
    Iterator<?> it = list.iterator();
    while (it.hasNext()) {
        Object curObj= it.next();
        if (curObj == remObj) {
            it.remove();
            break;
        }
    }
}

当上面的代码可以发生在另一个循环中时,就会出现问题,该循环正在积极地迭代原始列表。

private void performChecks(){
    for(Object obj : list){
        //perform series of checks, which could result in removeMethod 
        //being called on a different object in the list, not the current one
    }
}

如何在遍历列表时从列表中删除未知对象?

示例

我有一个监听器对象列表。在通知侦听器事件时,可能不再需要其他侦听器。

【问题讨论】:

  • 您是否尝试过使用增强的 for 循环和 .remove() 方法?还有同步课程?
  • 你的问题我不清楚。有什么例子吗?
  • removeMethod 的增强 for 循环?那会抛出一个ConcurrencyModificationExceptionError
  • 添加示例@BoratSagdiyev
  • @Mr_Skid_Marks 您能否添加一个示例以便我们生成您的问题?

标签: java list concurrency iterator


【解决方案1】:

如果我正确理解您的问题,以下将是可能的解决方案(可能不是最有效但我认为值得一试):

在 performChecks() 下使用for(Object obj : list.toArray())

优点:每次将列表“刷新”为数组时,它都会反映更改。 因此,如果该项目在单独的循环中从列表中删除

【讨论】:

    【解决方案2】:

    你的问题有点混乱,所以我会回答我认为我理解的;您的问题是这样的:如何在同时迭代列表并删除项目时从列表中删除项目或如何避免ConcurrentModificationException

    首先,您的代码中的问题是您使用迭代器而不是列表删除项目。其次,如果您使用并发,请使用 CopyOnWriteArrayList 并使用

    删除该项目

    list.remove()

    要为场景提供一个很好的例子,请查看this

    所以这不好:

    List<String> myList = new ArrayList<String>();
    
        myList.add("1");
        myList.add("2");
        myList.add("3");
        myList.add("4");
        myList.add("5");
    
        Iterator<String> it = myList.iterator();
        while(it.hasNext()){
            String value = it.next();
            System.out.println("List Value:"+value);
            if(value.equals("3")) myList.remove(value);
        }
    

    这很好:

    List<String> myList = new CopyOnWriteArrayList<String>();
    
        myList.add("1");
        myList.add("2");
        myList.add("3");
        myList.add("4");
        myList.add("5");
    
        Iterator<String> it = myList.iterator();
        while(it.hasNext()){
            String value = it.next();
            System.out.println("List Value:"+value);
            if(value.equals("3")){
                myList.remove("4");
                myList.add("6");
                myList.add("7");
            }
        }
        System.out.println("List Size:"+myList.size());
    

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 2022-05-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多