写如下 代码:
public static void testRemoveAll()
{
ArrayList theInterestUrls = new ArrayList();
theInterestUrls.add(2);
theInterestUrls.add(3);
theInterestUrls.add(4);
theInterestUrls.add(5);
theInterestUrls.add(6);
theInterestUrls.add(7);
List getList = theInterestUrls.subList(1, 3);
theInterestUrls.removeAll(getList); //trigger java.util.ConcurrentModificationException in JDK1.6 but ok in JDK1.7
for (Integer integer : theInterestUrls)
{
System.out.println(integer);
}
}
注意代码中的注释,在 JDK1.6下注释行将触发 java.util.ConcurrentModificationException 异常,而在 JDK1.7 下则是正常的。原因在于,JAVA 实现的 subList 都是引用,且在 JDK1.6 里面,collection 执行 subList 后,又执行 removeAll(targetList) ,这个方法是在 collection 中查找出现在 targetList 中的所有元素再删除。而JDK1.6 的实现可能没有处理这种情况,如果 targetList 就是自己的一部分,该怎么处理。而 JDK1.7 作了这样的处理,所以可以。
上述代码最好的写法是将 theInterestUrls.removeAll(getList); 这句换为 getList.clear();
本文通过一个具体的代码示例,对比了Java JDK1.6与JDK1.7中使用subList与removeAll方法的不同行为,解释了在JDK1.6中为何会触发java.util.ConcurrentModificationException异常,而在JDK1.7中则不会。
4092

被折叠的 条评论
为什么被折叠?



