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?
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?
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.
clear() doesn't reallocate a new object, so it's less of a performance hit.
Imagine the situation where there is multiple references of the same java.util.ArrayList
throughout your code. It would be almost impossible or very difficult to create new instance of the list and assign to all the variables. But java.util.ArrayList.clear()
does the trick!
You might have a final field (class variable) List
:
private final List<Thing> things = ...
Somewhere in the class you want to clear (remove all) things. Since things
is final it can't be reassigned. Furthermore, you probably don't want to reassign a new List instance as you already have a perfectly good List instantiated.
You pay less with clear than you do with creating a new object if your objective was to really clear.
Reassigning a reference doesn't clear the object. The assumption is that if there are no other references to it, it would be reclaimed by the GC relatively soon. Otherwise, you just got yourself a mess.
In addition to the reasons mentioned, clearing a list is often more semantically correct than creating a new one. If your desired outcome is a cleared list, the action you should take is to clear the list, not create a new list.