java中ArrayList.clear()和ArrayList.removeAll()之间的区别?
Java中的ArrayList类是List接口的Resizable-array实现。它允许空值。
此类的clear()方法从当前List对象中删除所有元素。
示例
import java.util.ArrayList;
public class ClearExample {
public static void main(String[] args){
//Instantiating an ArrayList object
ArrayList<String> list = new ArrayList<String>();
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("Impala");
System.out.println("Contents of the Array List: \n"+list);
//Removing the sub list
list.clear();
System.out.println("Contents of the ArrayList object after invoking the clear() method: "+list);
}
}输出结果
Contents of the Array List: [JavaFX, Java, WebGL, OpenCV, Impala] Contents of the ArrayList object after invoking the clear() method: []
而ArrayList类的removeAll()方法接受另一个集合对象作为参数,并从当前ArrayList中删除其所有内容。
示例
import java.util.ArrayList;
public class ClearExample {
public static void main(String[] args){
//Instantiating an ArrayList object
ArrayList<String> list1 = new ArrayList<String>();
list1.add("JavaFX");
list1.add("Java");
list1.add("WebGL");
list1.add("OpenCV");
list1.add("OpenNLP");
list1.add("JOGL");
list1.add("Hadoop");
list1.add("HBase");
list1.add("Flume");
list1.add("Mahout");
list1.add("Impala");
System.out.println("Contents of the Array List1 : \n"+list1);
ArrayList<String> list2 = new ArrayList<String>();
list2.add("JOGL");
list2.add("Hadoop");
list2.add("HBase");
list2.add("Flume");
list2.add("Mahout");
list2.add("Impala");
System.out.println("Contents of the Array List1 : \n"+list2);
//Removing elements
list1.removeAll(list2);
System.out.println("Contents of the Array List after removal: \n"+list1);
}
}输出结果
Contents of the Array List1 : [JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala] Contents of the Array List1 : [JOGL, Hadoop, HBase, Flume, Mahout, Impala] Contents of the Array List after removal: [JavaFX, Java, WebGL, OpenCV, OpenNLP]