I was looking through the Java documentation, and I came across the clear() method of ArrayLists.
What's the use of this, as opposed to simply reassigning a new ArrayList object to the variable?
clear() method is used to remove all the elements from a Set. Using the clear() method only clears all the element from the set and not deletes the set.
clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.
Its usefulness with ArrayList:It allows various features of ArrayList such as dynamic sizing and implementation of associated functions which are only defined on class objects. Without a wrapper class it will be very difficult to implement an ArrayList.
The clear() method removes all the elements of a single ArrayList . It's a fast operation, as it just sets the array elements to null . The removeAll(Collection) method, which is inherited from AbstractCollection , removes all the elements that are in the argument collection from the collection you call the method on.
Because there might be multiple references to the one list, it might be preferable and/or more practical to clear it than reassigning all the references.
If you empty your array a lot (within, say, a large loop) there's no point creating lots of temporary objects. Sure the garbage collector will eventually clean them up but there's no point being wasteful with resources if you don't have to be.
And because clearing the list is less work than creating a new one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With