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?
First, use
Mapinstead ofHashtable. Second, you can use theMap#removemethod to free the reference of the key from memory. Note that you will remove the key/value pair from theMapbut the object will be alive until the GC decides to collect it.Explanation about
MapvsHashtable:Note that both
HashMapandHashtableare implementations of theMapinterface.