How to delete an array properly in Java

Chronus :

I'm 4 days old in Java and from the tutorials I've searched, the instructors focus a lot of effort in explaining how to allocate a two dimensional array (e.g.) as such:

Foo[][] fooArray = new Foo[2][3];

... but I've not found any that explains how to delete them.

From what is going on memory-wise, the variable fooArray will point to a block of memory in the heap, in which there are 2 elements. Each of the elements points to another block in the heap as well, which have 3 elements.

That being said, could I just reference the first block of elements and the garbage collector will do the job?

Foo[1] = null; and Foo[2] = null;

Or do I have to null each of the instantiated Foo elements?

Foo[1][1] = null; Foo[1][2] = null; Foo[1][3] = null; ...

Zabuza :

Explanation

You can not explicitly delete something in Java. It is the garbage collectors job to do that. It will delete anything which is not used anymore by anyone. So either

  1. let the variable fall out of scope or
  2. assign null
  3. or any other instance to it.

Then the array instance (as well as its subarrays) is not referenced anymore and the garbage collector will delete it eventually.


References

To understand why re-assigning the outer array is enough to also delete the inner arrays, you need to understand how they are referenced. Again, the garbage collector can delete anything which is unreachable. So let's take a look at an array such as:

int[][] outer = {{1, 2}, {3, 4}, {5, 6}};

We have 4 array instances. One is of type int[][] and three of type int[]. Also, we have one variable outer. The instances are referenced as follows:

                       ___> {1, 2}
                      |
outer  --> int[][] ---|---> {3, 4}
                      |
                      |___> {5, 6}

So by deleting outer, nobody references int[][] anymore. The garbage collector can now delete it. But that also removes all references to the inner arrays, so the garbage collector can now also delete them.

Now assume that you would reference one of the inner arrays by another variable:

int[][] outer = {{1, 2}, {3, 4}, {5, 6}};
int[] thirdInner = outer[2];
other = null; // remove the reference

The situation is now

outer  --> null

                       ___> {1, 2}
                      |
           int[][] ---|---> {3, 4}
                      |
                      |______> {5, 6}
                          |
thirdInner _______________|

So the garbage collector will now delete the outer array int[][], which also removes all references to the first and second inner array. But the third is still referenced by thirdInner, so after garbage collection we have:

outer       --> null
thirdInner  --> {5, 6}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36023&siteId=1