Difference between null and clear in an ArrayList

5

What's the difference between:

arrayList.clear();

and

arrayList = null;

Do not both destroy all elements of the ArrayList?

    
asked by anonymous 29.08.2014 / 05:39

1 answer

7

No.

As the name itself says the first one clears all elements (it makes the elements null ) and the ArrayList passes have zero elements ( size is changed) and you can continue to manipulate it. It does not mean it will save memory.

The second destroys the reference in this variable (places a reference to 0) preventing it from accessing the ArrayList object and making it impossible for you to use it with this variable. You can even create another object and store it in the same variable, but it will be a new object. If there are no more references to this object it stays in memory, unavailable, until the garbage collector collects it from memory. The variable (that is, the reference to the object that will be 0 until it points to an object) continues to exist and until another object is bound to it, nothing can be done except to store a new object ArrayList allowing all operations that this class can perform.

You may think the result is the same. And it may even be depending on what you want. Conceptually the first one makes more sense if you want to clear the elements and start over with ArrayList . Setting% with% in a variable null means you no longer need it and it is usually unnecessary.

In Java and many modern languages (which have a GC tracker) it is often unnecessary to take any action to say that you do not need more than one variable and that you no longer want a reference to an object, just stop using it. Of course there may be cases where you know it will take too long or there will never be release of this variable and this can be considered a leak and memory and setting ArrayList to this variable may be an option to free memory if you know it is the only reference for the object.

It is a rare situation but it is good to know that even with GC there is the possibility of memory leakage, and how to deal with it. I would not know all the examples in Java, but if the variable is static or is in an object (as a member or method) created and maintained at the beginning of the / thread application. In C # I know this leak can occur in events ( observer pattern ) if the programmer forget to release the object at the time of the last unsubscribe .

These codes have "more equivalent" results:

arrayList.clear();

and

arrayList = null;
arrayList = new ArrayList();

In this way, the following operations above the variable null can be done in the same way in a arrayList "clean". But the same result was achieved with different techniques with different characteristics and different performance, although it is small and probably irrelevant in most cases. The second can generate more pressure in the GC.

    
29.08.2014 / 06:09