lfaraone
lfaraone

Reputation: 50672

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?

Upvotes: 5

Views: 3044

Answers (6)

Steve Kuo
Steve Kuo

Reputation: 63064

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.

Upvotes: 3

Matthew Olenik
Matthew Olenik

Reputation: 3577

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.

Upvotes: 2

cletus
cletus

Reputation: 625037

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.

Upvotes: 14

Uri
Uri

Reputation: 89729

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.

Upvotes: 2

Tomasz Blachowicz
Tomasz Blachowicz

Reputation: 5843

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!

Upvotes: 2

Kevin Herron
Kevin Herron

Reputation: 6985

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

Upvotes: 1

Related Questions