What is the difference between ArrayList.clear() and ArrayList.removeAll()?

前端 未结 9 1746
不思量自难忘°
不思量自难忘° 2020-11-30 16:05

Assuming that arraylist is defined as ArrayList arraylist, is arraylist.removeAll(arraylist) equivalent to arraylist.clear()?

相关标签:
9条回答
  • 2020-11-30 17:04

    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()?

    0 讨论(0)
  • 2020-11-30 17:05

    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.

    0 讨论(0)
  • 2020-11-30 17:12

    They serve different purposes. clear() clears an instance of the class, removeAll() removes all the given objects and returns the state of the operation.

    0 讨论(0)
提交回复
热议问题