"Closed" HashMap in Java/Scala

collections, hashmap, java, scala

Solution

How is this concept called?

Identity map. It won't call `equals()` when looking for elements and just use identity (i.e. `==`).

The correct solution isn't to "fix" the map but to use only keys which use the default `Object.equals()`:

public boolean equals( Object other ) { return this == other; }

The problem is that finding elements in this map can be problematic unless all keys are singletons. So you can't use `String`, for example, because Java doesn't guarantee that all string instances are interned. The same is true for `Integer`: Instances < -128 and > 127 will be different.

But if you use your own optimized implementation for keys, you can solve this.

Problem

Very often the performance bottleneck when using hash maps is the `equals` method. `equals` can be very expensive for deep data structures. Note, that the following is about immutable hash maps. Thus, at least you will never remove a key. I think adding keys should be ok. Unsafe `get` Suppose you query a hash map, being certain it contains the queried key. Then if there is no collision for the given key, the found single entry can be returned just based on the hash hit, because it has to be the queried object. This can avoid calling `equals` in `get` in most cases (when there is no collision). Questions - How is this concept called? - Are there any hash map implementations available for Java or Scala, that support such an unsafe `get` operation? Btw, I'm open for suggestions of a better subject line.

Original source

Related problems