Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are immutable objects in hashmaps so effective?

So I read about HashMap. At one point it was noted:

"Immutability also allows caching the hashcode of different keys which makes the overall retrieval process very fast and suggest that String and various wrapper classes (e.g., Integer) provided by Java Collection API are very good HashMap keys."

I don't quite understand... why?

like image 761
Toskan Avatar asked Apr 26 '12 23:04

Toskan


People also ask

Why are immutable objects better?

Immutable objects are also useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.

Why is it suggested to have immutable object as key in HashMap?

Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap.

Are immutable objects more efficient?

Strings immutability makes it possible to share them, this is more efficient memory-wise.

Why does hashing only work with immutable objects?

Dicts and sets must use a hash for efficient lookup in a hash table; the hash values must be immutable, because changing the hash will mess up the data structures and cause the dict or set to fail.


1 Answers

String#hashCode:

private int hash;  ...  public int hashCode() {     int h = hash;     if (h == 0 && count > 0) {         int off = offset;         char val[] = value;         int len = count;          for (int i = 0; i < len; i++) {             h = 31*h + val[off++];         }         hash = h;     }     return h; } 

Since the contents of a String never change, the makers of the class chose to cache the hash after it had been calculated once. This way, time is not wasted recalculating the same value.

like image 105
Jeffrey Avatar answered Oct 03 '22 04:10

Jeffrey