Reputation: 5177
I have a small question regarding a Hash Table. Suppose i have a String as a key and a complex object as a value stored in a Hash Table.
Now i use "get" to obtain the object from the same Hash Table. Now if the variable that i stored the reference of the object that i got from the Hash Table is set to null, this would have no affect on the memory of the object in the Hash Table. How can i destroy the object in the Hash Table?
One way might be to put null as the value for my given key ? Is there another other more elegant way?
Upvotes: 2
Views: 474
Reputation: 62906
Class instances (=objects) stay in memory, references to the instance are stored in variables and in HashMap values. When no references remain to the instance, then at some point Java VM garbage collector may free the memory, if it feels like it.
A reference disappears when the variable it is in gets new value (another instance or null), or goes out of scope. So, if you want to get rid of an instance in a Map value, you can either remove its key from map, or keep the key but set value to null. Usually you remove, keeping nulls in a Map is usually not something you want to do unless you have to. If no other reference remain, then instance becomes eligible for garbage collection.
Note about difference to C++: in Java there is no destructor for cleanup (finalize method is not guaranteed to be called ever). If a Java class has resources like files or network connections that should be closed when done, then the class needs a close method, and the programmer is responsible of calling it explicitly (often in try...finally block even if there is no catch), when he's done with the object.
Upvotes: 2
Reputation: 85789
First, use Map
instead of Hashtable
. Second, you can use the Map#remove
method to free the reference of the key from memory. Note that you will remove the key/value pair from the Map
but the object will be alive until the GC decides to collect it.
Explanation about Map
vs Hashtable
:
Note that both HashMap
and Hashtable
are implementations of the Map
interface.
Upvotes: 1