Java ArrayList removeAll() 方法
目录
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("Runoob"); sites.add("Taobao"); System.out.println("网站列表: " + sites); // 删除所有元素 sites.removeAll(sites); System.out.println("所有 removeAll() 方法后: " + sites); } }
执行以上程序输出结果为:
网站列表: [Baidu, Mybj, Taobao] 所有 removeAll() 方法后: []
在上面的实例中,我们创建了一个名为 sites
的动态数组。该动态数组存储着网站的名称。
注意这一行:
sites.removeAll(sites);
sites
作为 removeAll()
方法的参数。
注意:clear()
是动态数组中删除所有元素的最好方法。要了解更多信息,请访问 Java ArrayList clear()。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Java ArrayList removeAll() 方法
码云笔记 » Java ArrayList removeAll() 方法