ArrayList clear Vs removeAll
ArrayList can be emptied or cleared using either clear or removeAll method. Both these methods differ in performance.
If you see the code for both these methods you will get to know which method is faster and better in terms of performance.
1. clear method code
1 2 3 4 5 6 7 8 | public void clear() { modCount++; for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } |
2. removeAll method code
1 2 3 4 5 6 7 8 9 10 11 | public boolean removeAll(Collection<?> c) { boolean modified = false; Iterator<?> e = iterator(); while (e.hasNext()) { if (c.contains(e.next())) { e.remove(); modified = true; } } return modified; } |
As you can see clear() uses O(n) and removeAll() uses O(n^2). This makes clear method more faster.
Lets see examples that will show difference in performance of arraylist clear vs removeAll method.
Example : ArrayList clear Vs removeAll
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package com.kscodes.sampleproject; import java.util.ArrayList; import java.util.List; public class ArrayListClearTest { public static void main(String[] args) { //Create 2 arraylists with 10000 elements List<Integer> arrList1 = new ArrayList<>(); List<Integer> arrList2 = new ArrayList<>(); for (int i = 0; i < 10000; i++) { arrList1.add(i); arrList2.add(i); } //Measure time of clear method using one arraylist System.out.println("Size of ArrayList 1 :: " + arrList1.size()); long startTime1 = System.currentTimeMillis(); arrList1.clear(); long endTime1 = System.currentTimeMillis(); System.out.println("Time required to clear ArrayList 1 using clear() ::"+ (endTime1-startTime1)); //Measure time of removeAll method using another arraylist System.out.println("Size of ArrayList 2 :: " + arrList2.size()); long startTime2 = System.currentTimeMillis(); arrList2.removeAll(arrList2); long endTime2 = System.currentTimeMillis(); System.out.println("Time required to clear ArrayList 2 using removeAll() ::"+ (endTime2-startTime2)); } } |
Output
1 2 3 4 | Size of ArrayList 1 :: 10000 Time required to clear ArrayList 1 using clear() ::0 Size of ArrayList 2 :: 10000 Time required to clear ArrayList 2 using removeAll() ::141 |
As you can see time taken by removeAll() method is much greater than clear() method.