tag:blogger.com,1999:blog-8712770457197348465.post8677549658142457466..comments2024-03-29T03:17:04.645-07:00Comments on Javarevisited: How to empty an ArrayList in Java? clear() vs removeAll() method Example Tutorialjavin paulhttp://www.blogger.com/profile/15028902221295732276noreply@blogger.comBlogger4125tag:blogger.com,1999:blog-8712770457197348465.post-33909222295812607042020-04-30T21:59:35.160-07:002020-04-30T21:59:35.160-07:00@Saikat, you have got a point there and clear shou...@Saikat, you have got a point there and clear should be used to empty the collection, while removeAll(), though it can also empty the collection is best to remove a subset of elements. javin paulhttps://www.blogger.com/profile/15028902221295732276noreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-46348026242405246652020-04-29T21:27:51.986-07:002020-04-29T21:27:51.986-07:00Don't think this is the reason. This is not ab...Don't think this is the reason. This is not about performance. The both methods have different meaning. <br /><br />@Test<br />void whenClear_thenListBecomesEmpty() {<br /> Collection collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));<br /> <br /> collection.clear();<br /> <br /> assertTrue(collection.isEmpty());<br />}<br /><br />As we can see the collection is empty Saikathttps://www.blogger.com/profile/16530818423154533135noreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-80081275722329874322015-11-11T03:26:21.095-08:002015-11-11T03:26:21.095-08:00removeAll() is O(n^2) but not for the reason you m...removeAll() is O(n^2) but not for the reason you mention. Calling 'contains()' is O(n) as an average. When you call 'al.removeAll(al)' on an array list on itself the call to 'contains()' finds the first element in one iteration, and that is O(1). That would make the it still O(n). The quadratic performance comes from the array nature of array list: each time an element is Verhás Péterhttps://www.blogger.com/profile/06377161363854132582noreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-63435584494988445802015-10-25T21:25:32.587-07:002015-10-25T21:25:32.587-07:00I think these two methods got totally diferent mea...I think these two methods got totally diferent meaning and purpose. Like clear() removes all elements and resets the collection where as removeAll(Collection c) takes a input parameter and removes the elements that we passed to the method. So we use clear() to remove all elements where as removeAll(Collection c) is used when we want a list of elements to be removed. <br /><br />So the point what Anonymousnoreply@blogger.com