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循环时,它总是抛出一个.为什么?我确信当它在服务方法中运行时没有两个线程正在访问集合那么是什么导致两个场景中的区别在于它被抛入一个而不是另一个?
我ConcurrentModificationException在运行你的代码时得到了一个(在修复了几个拼写错误之后).
你不会得到的唯一场景ConcurrentModificationException是:
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)
| 归档时间: |
|
| 查看次数: |
153 次 |
| 最近记录: |