While doing some researches about how to pass a object reference in android I was thinking about the following.
Let's assume I have a WeakHashmap with Long as keys. And now I put one Object into this WeakHashMap and assign it to the key 'new Long(1)' (assuming that I will save the reference to this Long).
Now another part of the application creates a new Long(1) and after that I set my first Long (that was used as key) to null.
A weak reference will be garbage collected when there are no strong references to the memory.
Now, your example. This a little tricky. From the javadoc for Long
, the valueOf
method improves performance by "caching frequently requested values". This means that it will make a difference to the answer whether you use valueOf
or new
.
In your case you use new
so each new Long(1)
will be a different object - i.e. a different reference. But this is something to bear in mind - Integer
, Long
and the other wrapper types are usually cached by the JVM may not behave as you expect in a WeakHashMap
. String
s are interned so they are also problematic.
Anyway, to answer your questions:
Long
then the mapping will be GC'ed at the next opportunity.HashMap
uses hashcode
and equals
for comparison. A TreeMap
uses compareTo
. In any case it would make no difference, this is about references not about any concept of equality. If there are no more strong references to your object then the mapping will be GC'ed.Map
uses hashcode
and equals
when checking whether a key is already in the Map
. The Weak
part is talking about references. Two objects can be equals
but not ==
.You can use a PhantomReference
to track when your key is GC'ed. That might help you understand how weak references work.