3

I don't understand, why does WeakHashMap hashes keys by their hashCode() and identifies by equals()?

By contract of this class, it can used to tie any instance to any other instance. From my opinion, this implies hashing and comparing by identity.

Event in the doc there is a note about confusing usage with such class as String:

This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.

So, is there any implementation of this class, in some collections library, where it is hashed by identity?

Dims
  • 47,675
  • 117
  • 331
  • 600
  • 1
    There's `IdentityHashMap`, but it's not weak. – Kayaman Jun 15 '16 at 12:31
  • Yes true, it is not weak – Dims Jun 15 '16 at 12:33
  • Why do you need a weak identitymap? Is your use case special, or were you just confused by the documentation? `HashMap` allows you to use anything as keys/values, and it doesn't use identity either. – Kayaman Jun 15 '16 at 12:36
  • Suppose I need to add runtime field to `ArrayList<>`. I would create `WeakHashMap,MyFieldType>` and access it from there. These fields were automatically disappear along with `ArrayList<>` instances. Unfortunately, `hashCode()` of list calculates hash based on all list elements, `WeakHashMap` utilizes namely it, and `WeakHashMap#hash()` is made `final`. I regard is as bad design. – Dims Jun 15 '16 at 15:03
  • In other words, please suppose your own usecase of `WeakHashMap`, where keys should be compared by content. – Dims Jun 15 '16 at 15:05
  • 1
    I'm not sure I still understand your usecase, but having a `Collection` as a key would be bad for the hashing. However the "add runtime field to ArrayList" sounds a bit dubious too, design wise. – Kayaman Jun 16 '16 at 06:27
  • What other goals (than that dubious one) `WeakHashMap` can achieve? – Dims Jun 16 '16 at 13:02
  • Well it's a popular choice for caches. This is the first time I've ever heard of anyone adding fields to `ArrayList` at runtime. Sounds like some funky design. – Kayaman Jun 16 '16 at 13:07
  • I don't see how this is good for caching. Weak values would be better for caching, not weak keys. If you don't like adding field to `List` then regard adding field to a `Thread`. – Dims Jun 16 '16 at 14:45
  • It does require trickery (and keys with reference equality), and looks like I omitted the "home-grown" part (you wouldn't use a self-made cache in real work, would you?). However I'm much more intrigued by your "add fields to JDK classes during runtime" concept. – Kayaman Jun 17 '16 at 06:33

0 Answers0