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

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.)

Leave a Comment