Java: hashmap.remove(key)

JianJunShen
JianJunShen used Ask the Experts™
on
Hi: I have a data structure. In the data structure, I have five hashmaps. IN every hashmap, there is key and value pair. May I put 5 hashmap keys all point to same object. I put hashmap1.put(key1, sameobject), hashmap2.put(key2,sameobject), hashmap3.put(key3, sameobject)....

When I remove it, I remove hashmap1.remove(key1), hashmap2.remove(key2), hashmap3.remove(key3),... does that mean
1) In  hashmapX.remove(keyX):..... I only delete reference. Garbage collection will remove sameobject.
2) In hashmap1.remove(key1), I already removed sameobject, all other keys are dead. Hence memory leak comes.

Which case 1), 2) is true?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Only the mapping is remove from an individual Map. Nothing else is affected

Author

Commented:
You mean only reference is removed. And it will wait for garbage collection to release sameobject's memory. Am I right?
Only reference is removed, object is not destroyed to be garbage collected.

Top Expert 2016
Commented:
>>And it will wait for garbage collection to release sameobject's memory. Am I right?

It has nothing to do with the object really. All that happens is that the object's reference count is decremented by 1. If that *had* been the only reference to that object, then yes, it would be garbage collected, but that's actually not very likely in practice, unless it's by design
In java some object is garbage collected when there is no any other references to it.
By adding one and the same object to 5 different maps means that there are 5 different references to it.
You have to remove the object from all of the maps and then it will be garbage collected.
Top Expert 2016

Commented:
:-)
thanks for the points

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial