一个让我很纠结的问题。关于容器的分片问题。。
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, 修改sublist能影响到list
* 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>/
list.removeAll(sublist);
sublist.clear();
boolean removeAll(Collection<?> c)
从列表中移除指定 collection 中包含的其所有元素(可选操作)。