Reputation: 131
I have written a program for sorting an integer type array which involves the creation another array of the same size. After sorting, there is no use of the new array, so I want to completely get rid of it. So far, I've only found questions relating to the deletion of specific types of elements. Some help?
Information (if needed):
Original Array: A[n]
New Array: B[n]
B[n]
has to be completely deleted.
Upvotes: 3
Views: 45726
Reputation: 11
Normally the gc() frees the memory which has no references. But you can also free the memory with array = null
.
Upvotes: 1
Reputation: 363
Set B to null. B = null;
This way the garbage collector will clean it up whenever it runs. While you can't control when garbage collection happens since each JVM might have it's own garbage collection algorithm, you may suggest to the system that it should run the garbage collector to free up some memory.
You can do this by using System.gc();
Note: As mentioned above, System.gc(); will only suggest that garbage collection be carried out but does not assure it.
Upvotes: 1
Reputation: 17595
If the array is locally defined in your sorting method then it will be scheduled for garbage collection when your method ends as there will be no existing reference to it.
If it is a class or instance variable then set all references to it to null
.
In Java you dont have to worry about memory deallocation. There is no such stuff like C's stdlib free(void*)
or C++'s delete[]
operator. Thee is only the garbage collector.
Upvotes: 0
Reputation:
Array is a reference type in Java. You can make an array reference null
if you no longer wish to use it:
arr = null;
Upvotes: 5
Reputation: 46209
The temp array will be "deleted" (or more correctly, the occupied memory will be eligible for garbage collection) automatically whenever you leave the method performing the sorting (assuming of course that the temp array is created inside the method).
There is almost never any need for explicit memory deallocation in Java
.
Upvotes: 8