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:
- if there are no more strong references to you original
Long
then the mapping will be GC'ed at the next opportunity. - I think you are confused here. A
HashMap
useshashcode
andequals
for comparison. ATreeMap
usescompareTo
. 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. - No it would not. As I said in 2. - the
Map
useshashcode
andequals
when checking whether a key is already in theMap
. TheWeak
part is talking about references. Two objects can beequals
but not==
.
You can use a PhantomReference
to track when your key is GC'ed. That might help you understand how weak references work.