To remove all items from a list, I can do it in two ways: lista.clear()
and lista = new ArrayList<T>()
.
What are the differences between them?
In which situations should I use each?
To remove all items from a list, I can do it in two ways: lista.clear()
and lista = new ArrayList<T>()
.
What are the differences between them?
In which situations should I use each?
When you use list.clear()
you actually clean the list and take advantage of the same memory space where it is already allocated.
list = new ArrayList<>()
you create a new instance in memory (another space to store the list) and assign this new address to the list that you reference, in this way it is the responsibility of the garbage collector to remove the instance that will no longer be used in memory. If you want to create a new list, but do not want to have the side effect of clearing the current list, create a new variable. This can be useful when the list
variable is shared and you do not want to tinker with its contents.
If list
is not used elsewhere, the best for optimization and performance is to use list.clear()
.