Java 教程 Java ArrayList removeAll() 方法

yale · 2022-05-29 01:12:44 · 热度: 10

removeAll() 方法用于删除存在于指定集合中的动态数组元素。

removeAll() 方法的语法为:

arraylist.removeAll(Collection c);

注:arraylist 是 ArrayList 类的一个对象。

参数说明:

  • c - 动态数组列表中要删除的元素集合

返回值

如果从动态数组成功删除元素返回 true。

如果动态数组中存在的元素类与指定 collection 的元素类不兼容,则抛出 ClassCastException 异常。

如果动态数组中包含 null 元素,并且指定 collection 不允许 null 元素,则抛出 NullPointerException 异常。

实例

从动态数组列表中删除所有元素:

实例

import java.util.ArrayList;

class Main {
    public static void main(String[] args){

        // 创建一个数组
        ArrayList<String> sites = new ArrayList<>();

            sites.add("Google");
            sites.add("Codercto");
            sites.add("Taobao");
            System.out.println("网站列表: " + sites);

        // 删除所有元素
        sites.removeAll(sites);
        System.out.println("所有 removeAll() 方法后: " + sites);
    }
}

执行以上程序输出结果为:

网站列表: [Google, Codercto, Taobao]
所有 removeAll() 方法后: []

在上面的实例中,我们创建了一个名为 sites 的动态数组。该动态数组存储着网站的名称。

注意这一行:

sites.removeAll(sites);

sites 作为 removeAll() 方法的参数。

注意:clear() 是动态数组中删除所有元素的最好方法。要了解更多信息,请访问 Java ArrayList clear()

查看更多 Java ArrayList 方法 相关内容

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册