0

I was looking into some Java code from a large project and after a computational expensive loop that used an ArrayList I saw this:

list.clear();
list = null;

I know that the Garbage Collector is automatically triggered when an object is not referenced anymore, so my question is this: does the above code de-references the object so as the GC would delete it later on? From my experience, clearing a list is actually the procedure of nulling all of its elements and nulling the list, de-references the object of it. Is this procedure preferred over leaving the object without any clearance? The above section of the code is followed by a large number of functions and calls, so if my assumption is correct and the list is effectively un-referenced, the GC will be activated earlier on and free up useful memory.

Lefteris008
  • 899
  • 3
  • 10
  • 29
  • 3
    `list.clear()` is a waste of effort if you're immediately going to set the `list` variable to null, **unless** there are other references to the list somewhere else. – khelwood Jul 11 '16 at 08:29
  • Yes, but this list contains custom created objects. So, clearing its contents actually voids any reference of them and then assigning a `null` value, de-references the list object itself. – Lefteris008 Jul 11 '16 at 08:31
  • And also http://stackoverflow.com/questions/2931170/does-variable-null-set-it-for-garbage-collection – Suresh Atta Jul 11 '16 at 08:32
  • @Lefteris008 That's irrelevant. If you don't have any references left to the list itself, it doesn't matter what the list still has references to. That doesn't protect them from garbage collection. – khelwood Jul 11 '16 at 08:45
  • @khelwood OK, thanks for the info! – Lefteris008 Jul 11 '16 at 08:55

0 Answers0