There are two ways to empty an ArrayList – By using ArrayList.clear() method or with the help of ArrayList.removeAll() method. Although both methods do the same task the way they empty the List is quite different.
Lets see the below example first then we will see the implementation and difference between clear() and removeAll().
package beginnersbook.com; import java.util.ArrayList; import java.io.*; public class Details { public static void main(String [] args) { ArrayList<String> al1=new ArrayList<String>(); al1.add("abc"); al1.add("xyz"); System.out.println("ArrayList before clear: "+al1); al1.clear(); System.out.println("ArrayList after clear: "+al1); ArrayList<String> al2=new ArrayList<String>(); al2.add("text 1"); al2.add("text 2"); System.out.println("ArrayList before removeAll: "+al2); al2.removeAll(al2); System.out.println("ArrayList before removeAll: "+al2); } }
Output:
ArrayList before clear: [abc, xyz] ArrayList after clear: [] ArrayList before removeAll: [text 1="text" 2="2" language="1,"][/text] ArrayList before removeAll: []
As you can both the methods did the same job, they emptied the ArrayList. It’s time to determine which method gives good performance.
The actual code of clear() method:
public void clear() { for (int i = 0; i < size; i++) arraylist[i] = null; size = 0; }
Here arraylist is an instance of ArrayList class.
Code of removeAll() method:
public boolean removeAll(Collection c) { boolean ismodified = false; Iterator iterator = iterator(); while (iterator.hasNext()) { if (c.contains(iterator.next())) { iterator.remove(); ismodified = true; } } return ismodified; }
By seeing the code of both the methods we can very well say that clear() method gives better performance compared to the removeAll() method.
Performance of clear: O(n)
Performance of removeAll: O(n^2)
Koray says
I think there is a typo at 3th line of first output example;
“ArrayList before removeAll: [text 1, text 2]”
Rob says
I don’t understand how the performance of removeAll is O(n^2), it looks like the while loop would just visit every element of the array once, the same way the for loop in clear would. O(n^2) usually means nested loops, but I don’t see that in the implementation of removeAll.