java – Does ArrayList.clear() method frees memory?-ThrowExceptions

Exception or error:

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?

How to solve:

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.

###

No,It wont clear the memory.After you clear().

See the source code of clear()

 public void More ...clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
       elementData[i] = null;   
       size = 0;
    }

The method is making the elements eligible for Garbage Collector.Not clearing them immediately. Once GC run’s,They are gone.

###

clear only nulls backing array elements

public void clear() {
    modCount++;
    for (int i = 0; i < size; i++)
        elementData[i] = null;
    size = 0;
}

but if we call ArrayList.trimToSize after clear backing array will shrink

public void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (size < oldCapacity) {
        elementData = Arrays.copyOf(elementData, size);
    }
}

###

The answer to your question, it will not FREE the memory. It will just remove all the object references. Now these objects may or may not be collected by garbage collector depending on how they are referenced at other places.

For instance,

Object 1 refers - > Object 2
ArrayList refers - > Object 2
ArrayList refers - > Object 3

In this case, after Arraylist.clear(), object 3 will be eligible for clean-up but not object 2.

Leave a Reply

Your email address will not be published. Required fields are marked *