So the Java WeakHashMap
lets one create a map whose entries are removed if its keys become weak. But how can I create a Map whose entries are removed when the values in the map become weak? The reason I want to use a map is as a Global Hash Table which keeps track of objects according to their ID's.
ID ---> Object Address
Key ---> Value
(Where ID
is a text string)
I want key-value pairs to be removed when the object addresses become weak, not the Strings that point to them. Anyone any thoughts on this?
An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed.
HashMap remove() Method in Java HashMap. remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.
If you try to get something from the HashMap for a key that is not present in the map, the map returns null . That is true for any key you try to get from an empty map.
WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.
Such a map is supported, for example, in Guava:
Map<..., ...> m = new MapMaker().weakValues().makeMap();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With