这个情况下,removeAll成功的将1、2两个元素移除掉了。结果如下所示:
3
4
5
6
7
8
9
10
这到底是什么情况呢,为什么发生这种情况呢?莫着急,我们看一下removeAll底层的源码是如何实现的。ArrayList底层源码如下所示:
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull©;
return batchRemove(c, false);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {