JavaArrayList removeAll() 方法

ArrayList removeAll() 删除包含在指定方法参数集合中的所有匹配元素。

ArrayList removeAll() 方法

在内部,removeAll()方法迭代 arraylist 的所有元素。
对于每个元素,它将元素传递给参数集合的 contains()方法。

如果在参数集合中找到元素,它会重新排列索引。
如果未找到元素,则将元素保留在后备数组中。

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    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 {
        // 保持与AbstractCollection的行为兼容性,
        // 即使 c.contains() 抛出异常
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

包含要从此列表中删除的元素的方法参数集合。

如果此列表因调用而更改,则方法返回“true”。

如果此列表的元素的类与指定的集合不兼容,则方法抛出 ClassCastException
如果此列表包含空元素并且指定的集合不允许空元素,它也可能抛出 NullPointerException

https://onitroad.com 更多教程

ArrayList removeAll()方法 示例

Java 程序使用 removeAll() 方法从数组列表中删除所有出现的对象。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "A", "D", "A"));

        System.out.println(alphabets);

        alphabets.removeAll(Collections.singleton("A"));

        System.out.println(alphabets);
    }
}

程序输出。

[A, B, A, D, A]
[B, D]
日期:2020-09-17 00:09:56 来源:oir作者:oir