一个让我很纠结的问题。关于容器的分片问题。。
import java.util.*;
class A{
private static int counter;
private int count = counter++;
public String toString(){
return ("A : " + count);
}
}
class Test{
public static void main(String[] args){
A[] a = new A[10];
for(int i = 0;i < a.length;i ++)
a[i] = new A();
List<A> list = new ArrayList<A>(Arrays.asList(a));
System.out.println("list = " + list);
List<A> sublist = list.subList(list.size() / 4, list.size() / 2);
System.out.println("sublist = " + sublist);
list.removeAll(sublist); //为什么会出现异常???
sublist.clear(); //这里是对sublist进行clear,怎么会影响到最后list的输出呢??
System.out.println("finally : " + list);
}
}
由上述注释所示。好纠结啊。。。
------解决方案--------------------你打开sublist的源码,有注释的
/**The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations supported
* by this list.<p>/
, 修改sublist能影响到list
------解决方案--------------------这边会出现异常的原因是你的着两个方法起冲突了。
list.removeAll(sublist);
sublist.clear();
1.看api:
boolean removeAll(Collection<?> c)
从列表中移除指定 collection 中包含的其所有元素(可选操作)。
2.执行完removeall()完,sublist就为空了,编译器抛出(运行修改异常)
ConcurrentModificationException