Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usefulness of ArrayList<E>.clear()?

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?

like image 879
lfaraone Avatar asked May 05 '09 22:05

lfaraone


People also ask

What is the use of clear () in Java?

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.

What is the difference between ArrayList Clear () and removeAll () methods?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

Why are they useful for Arraylists?

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.

How do you clear an ArrayList method?

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.


1 Answers

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.

like image 105
cletus Avatar answered Oct 17 '22 16:10

cletus