Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ArrayList.clear() method frees memory? [duplicate]

If I'm not mistaken, ArrayList contains the value of memory locations in which the variables you've added to the List are stored. So, my assumption is that when you call ArrayList.clear() method it only frees the aforementioned values (of memory locations) but doesn't free those memory locations themselves. I'll try to illustrate this with an example:

Let's say you've got current status of memory:

[Memory location] (type of variable) *value*  [1000] (int) 32  [1002] (int) 12  [1003] (float) 2.5 

And you add them to the list myList, so it contains pointers to the 1000, 1002, 1003 memory locations.

When you call myList.clear() the pointers will be nullified, but the memory locations 1000, 1002, 1003 would still contain previously given values. Am I wrong?

like image 870
nstosic Avatar asked Aug 30 '13 08:08

nstosic


People also ask

What does clear do in ArrayList?

clear() method removes all of the elements from this list. The list will be empty after this call returns.

What is the difference between ArrayList Clear () and removeAll () methods?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.

What does list clear do?

Removes all elements from the List<T>.

Does List clear create a new list?

Actually, it will not create a new ArrayList in memory, instead it will replace the old list.


1 Answers

You are correct because the memory is cleared asynchronously by the Garbage collector, and not directly by such library functions. clear would only null them all out, and update the ArrayList state accordingly.

If any or all of those elements are not not referenced by any other portion of your code, they become eligible for garbage collection, and might be destroyed + de-allocated any time from shortly after that call to the end of time.

like image 95
Karthik T Avatar answered Sep 22 '22 05:09

Karthik T