Assuming that arraylist
is defined as ArrayList
, is arraylist.removeAll(arraylist) equivalent to arraylist.clear()?
Unless there is a specific optimization that checks if the argument passed to removeAll()
is the collection itself (and I highly doubt that such an optimization is there) it will be significantly slower than a simple .clear()
.
Apart from that (and at least equally important): arraylist.removeAll(arraylist)
is just obtuse, confusing code. It is a very backwards way of saying "clear this collection". What advantage would it have over the very understandable arraylist.clear()
?
clear() will be much more efficient. It will simply remove each and every item. Using removeAll(arraylist) will take a lot more work because it will check every item in arraylist to see if it exists in arraylist before removing it.
They serve different purposes. clear()
clears an instance of the class, removeAll()
removes all the given objects and returns the state of the operation.