1

当您使用 Java 1.5 现代 for 循环迭代集合并删除某些元素时,会引发并发修改异常。

但是当我运行以下代码时,它不会抛出任何异常:

    public static void main(String a []){
          Set<String> strs = new HashSet<String>();
          strs.add("one");
          strs.add("two");
          strs.add("three);

          for(String str : strs){
                   if(str.equalsIgnoreCase("two"){
                          strs.remove(str);
                   }
          }  
    }   

上面的代码不会抛出 ConcurrentModificationException。但是当我在我的 Web 应用程序服务方法中使用任何这样的 for 循环时,它总是抛出一个。为什么?我确信当它在服务方法中运行时没有两个线程正在访问集合那么是什么导致了两种场景中的差异,即它被抛出而不是另一个?

4

1 回答 1

8

ConcurrentModificationException在运行你的代码时得到一个(在修复了几个错别字之后)。

您不会得到 a 的唯一情况ConcurrentModificationException是:

  • 如果您删除的项目不在集合中,请参见以下示例:
  • 如果您删除最后一个迭代项(在 HashSet 的情况下不一定是最后添加的项)
public static void main(String[] args) {
    Set<String> strs = new HashSet<String>();
    strs.add("one");
    strs.add("two");
    strs.add("three");

    for (String str : strs) {
        //note the typo: twos is NOT in the set
        if (str.equalsIgnoreCase("twos")) {
            strs.remove(str);
        }
    }
}
于 2012-08-31T13:13:56.870 回答