views:

241

answers:

5

Many of the container type data structures in Java come with a clear() method. For example, we can call clear() on a Vector we want to clear out all the contents in the Vector. My question is after applying the clear() method, does the content in the vector get nulled out or are they still being referenced? Thanks.

+5  A: 

They are no longer referenced by the Collection, but if you have any references anywhere in your code, that reference continues to exist as it was.

As mentioned, Vector's source does call:

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

However, this is setting it's internal reference to null (pass-by-value) and will not affect any external references.

MarkPowell
+4  A: 

If not referenced from elsewhere, they will be garbage collected.

Fabian Steeg
+1  A: 
//Let gc do its work
for (int i = 0; i < elementCount; i++) 
    elementData[i] = null;

This is the code, with the comment from the Vector class. It answers the question, I think.

Bozho
+3  A: 

They don't get nulled out --this makes no sense, it's only the reference which becomes null, not the value--, they simply get dereferenced. If they don't have any other reference on it (e.g. another class having it referenced as a static or instance variable), then they will be eligible for GC.

BalusC
This is the best description of the implementation - the fact is that the collection never "had the objects" to begin with; it "had references" to the objects.
M1EK
+1  A: 

When it doubt, you can just take a look at the source code - it is bundled with the JDK (usually in a file named rt.zip).

public void clear() {
    removeAllElements();
}

public synchronized void removeAllElements() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}

The "Let gc do its work" comment is from the actual source, not mine.

matt b