为什么不抛出ConcurrentModificationException

Sha*_*yan 1 java collections exception

当您使用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);
                   }
          }  
    }   
Run Code Online (Sandbox Code Playgroud)

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

ass*_*ias 8

ConcurrentModificationException在运行你的代码时得到了一个(在修复了几个拼写错误之后).

你不会得到的唯一场景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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1如果删除最后一个迭代元素,则不会获得CME. (4认同)