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
- let the variable fall out of scope or
- assign
null
- 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}