Better practice to re-instantiate a List or invoke clear()

The way you are using it looks very much like how a Queue is used. When you work of the items on the queue they are removed when you treat them.

Using one of the Queue classes might make the code more elegant.

There are also variants which handle concurrent updates in a predictable way.


The main thing to be concerned about is what other code might have a reference to the list. If the existing list is visible elsewhere, do you want that code to see a cleared list, or keep the existing one?

If nothing else can see the list, I'd probably just clear it - but not for performance reasons; just because the way you've described the operation sounds more like clearing than "create a new list".

The ArrayList<T> docs don't specify what happens to the underlying data structures, but looking at the 1.7 implementation in Eclipse, it looks like you should probably call trimToSize() after clear() - otherwise you could still have a list backed by a large array of null references. (Maybe that isn't an issue for you, of course... maybe that's more efficient than having to copy the array as the size builds up again. You'll know more about this than we do.)

(Of course creating a new list doesn't require the old list to set all the array elements to null... but I doubt that that will be significant in most cases.)

Tags:

Java

List