Reputation: 3907
I have a long code. But the logic is as follows:
I have a 2-D array in Java. So, I have values inside locations: [0][0], [0][1], [0][2]
and values in:[1][0], [1][1], [1][2]
. At this point, I made some comparisons, and I am done from the first row. I want to free the memory of: [0][0], [0][1], [0][2]
and move to the next locations [2][0], [2][1], [2][2]
.
How can I do something like this. I can not overwrite [0][0], [0][1], [0][2]
,my code already programmed to move to the next row which is [2][0], [2][1], [2][2]
but I faced memory constraints and I want to free memory from the first row [0][0], [0][1], [0][2]
as I do not need it any more. I just need the current row and the previous to make a comparison. So, I want to delete the first row whenever I finish the comparison.
UPDATE:
I tried to assign NULL
to the unused array locations as the following:
for (int f = 0; f <= capacity; f++)
{
table[f][i-2] = (Integer) null;
}
My array is of type int and I only need the last two columns. The first one is not needed once I move one more position forward. When I applied the above code to assign NULL
, I got:
java.lang.NullPointerException
Upvotes: 0
Views: 266
Reputation: 29731
set null
to each reference in row
for (int i = 0; i < arr.length; i++)
{
arr[0][i] = null;
}
arr
should be array of references, not primal types
EDIT
for primal types (e.g. int
) you can use wrapper-class (e.g. java.lang.Integer
instead of int
: Integer[][]
instead of int[][]
)
EDIT2
Equivalent for previous loop is:
arr[0] = new Integer[arr.length];
array new Integer[arr.length]
contains null
values
Upvotes: 6
Reputation: 111399
Java doesn't have 2D arrays. They are mimicked by arrays whose elements are arrays.
You can set the first array of the array of arrays to null; this allows the GC to collect it and everything it contains.
arr[0]=null;
Note that this will work for arrays of both of arrays of primitive types and of objects. You don't need a loop.
An alternative to using null
is using an empty array:
// Assuming arr is int[][]
private static final int[] EMPTY_ROW = {};
...
arr[0] = EMPTY_ROW;
Using an empty array you may be able to avoid adding null-checks and use simpler code in general, while obtaining the same effects as with null
: the reference to the first row is removed, so it becomes eligible for garbage collection.
If you are interested in design patterns, this can be considered an application of the Null Object Pattern.
Upvotes: 4