Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear() methods in Java

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.

like image 348
flyingfromchina Avatar asked Nov 11 '09 19:11

flyingfromchina


People also ask

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 is the function of clear method?

The clear() method removes all the elements from a list.

Is Clear () collection interface?

The clear() of java. util. Collection interface is used to clear the Collection upon which it is called. This method does not take any parameter and does not returns any value.

How do you clear a string in Java?

StringBuffer: Java is popular. Updated StringBuffer: In the above example, we have used the delete() method of the StringBuffer class to clear the string buffer. Here, the delete() method removes all the characters within the specified index numbers.


1 Answers

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.

like image 103
MarkPowell Avatar answered Oct 02 '22 22:10

MarkPowell