views:

678

answers:

6

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?

+12  A: 

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.

cletus
Actually, there are cases where reusing a collection can cause memory problems. Briefly, if a large ArrayList (or similar) is kept around for a long time, it gets promoted to the tenured generation. Then any elements it contains that might be garbage in the young generation can't be collected without a full generation (which analyzes the tenured generation and can see that the elements are really garbage).
erickson
+1  A: 

clear() doesn't reallocate a new object, so it's less of a performance hit.

Kevin Herron
+2  A: 

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!

pregzt
+3  A: 

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.

Steve Kuo
+2  A: 

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.

Uri
+2  A: 

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.

Matt Olenik