list.clear() vs list = new Arraylist<T>()

Asked

Viewed 116 times

2

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 one?

  • @bigown I searched before and did not find. Thanks for the answers!

1 answer

6


When you use list.clear() you really clear the list and take advantage of the same memory space where it is already allocated.

When you use list = new ArrayList<>() vc creates a new instance in memory (another space to store the list) and assigns this new address to the list that you reference, so 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 variable list is shared and does not want to touch your content.

If list is not used elsewhere, the ideal for better optimization and performance is to use the list.clear().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.