写如下 代码:
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();