1

When I have come class

class MyClass1 {
    MyClass2 member;
}

ans it is garbage collected, then member also become eligible to garbage collection.

Can I simulate the same relation with Map?

So, I wish a map with weak references to keys. I.e. map itself should not prevent keys from garbage collection. And once key is garbage collected, then its associated value also become eligible to garbage collection.

Is this possible?

UPDATE

Is this just WeakHashMap?

glglgl
  • 89,107
  • 13
  • 149
  • 217
Dims
  • 47,675
  • 117
  • 331
  • 600
  • 3
    Yes, sounds like `WeakHashMap`. – khelwood Jun 07 '16 at 11:26
  • 2
    Possible duplicate of [When would you use a WeakHashMap or a WeakReference?](http://stackoverflow.com/questions/154724/when-would-you-use-a-weakhashmap-or-a-weakreference) – Didier L Jun 07 '16 at 11:27
  • As long as the value doesn’t hold a reference to the key. The bigger question is *why*? What are you actually trying to do? – Holger Jun 07 '16 at 17:10

1 Answers1

5

Absolutely. Just use a WeakHashMap, which will use weak references to keys and remove entries when keys are garbage collected.

Per Huss
  • 4,755
  • 12
  • 29