Assuming that arraylist is defined as ArrayList<String> arraylist, is arraylist.removeAll(arraylist) equivalent to arraylist.clear()?
If so, can I assume that the clear() method is more efficient for emptying the array list?
Are there any caveats in using arraylist.removeAll(arraylist) instead of arraylist.clear()?
The source code for
clear():The source code for
removeAll()(As defined inAbstractCollection):clear()is much faster since it doesn’t have to deal with all those extra method calls.And as Atrey points out,
c.contains(..)increases the time complexity ofremoveAllto O(n2) as opposed toclear‘s O(n).