Using an Integer
key in a WeakHashMap
doesn't prevent keys from being removed.
An Integer
key may be garbage collected once no references exist to the same Integer
instance that was put into the Map
. If there exist references to different Integer
instances equal (i.e. having the same numeric value) to a key in the WeakHashMap
, that doesn't prevent the key from being automatically removed.
Note that the value of your WeakHashMap
must not hold a strong reference to the key - otherwise the key can never be automatically removed. So to avoid that, simply add values to the WeakHashMap
as follows:
Integer key = new Integer(someObject.getID());
weakMap.put(key,someObject);
Now, once you no longer keep a reference to the Integer
instance referenced by the key
variable, the WeakHashMap
will be free to automatically remove it.
If you put
the entry in the WeakHashMap
without keeping a reference to the key (i.e. weakMap.put(new Integer(someObject.getID()),someObject)
), the WeakHashMap
will be able to auto-remove it immediately, which I don't think is what you wanted.