To reset ArrayList we have two options, one is to use clear() method and another is to use removeAll().
We dont need to worry if size of the ArrayList is small i.e. 10 to 100.
But if ArrayList size becomes huge the difference in the performance of clear() and removeAll() becomes
huge.
The best is to use clear(), as it provide us 0(n) performance on the other hand removeAll() gives 0(n^2)
performance.
public class Testing {
private static final int SIZELIST = 100000;
public static void main(String ar[]) {
ArrayList arrayList1 = new ArrayList(SIZELIST);
ArrayList arrayList2= new ArrayList(SIZELIST);
for (int i = 0; i < SIZELIST; i++) {
arrayList1.add(new Integer(i));
arrayList2.add(new Integer(i));
}
long timeStarting = System.nanoTime();
arrayList1.clear();
long timeElapsed = System.nanoTime() - timeStarting;
System.out.println("Time taken by clear to empty ArrayList of 1M elements (ns): " + timeElapsed);
timeStarting = System.nanoTime();
arrayList2.removeAll(arrayList2);
long timeElapse = System.nanoTime() - timeStarting;
System.out.println("Time taken by removeAll to reset ArrayList of 1M elements (ns): " + timeElapse);
}
}
Output:
Time taken by clear to empty ArrayList of 100000 elements (ns): 764537
Time taken by removeAll to reset ArrayList of 100000 elements (ns): 25372525252
0 Comment(s)