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.
views:
241answers:
5They 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.
If not referenced from elsewhere, they will be garbage collected.
//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.
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.
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.