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

2. removeAll method code

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

Output

As you can see time taken by removeAll() method is much greater than clear() method.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn