Open In App

Why does Java’s hashCode() in String use 31 as a multiplier?

How hashing is done?

Hashing

A hash works by allocating a value into one of the many storage spaces it has, allowing for fast retrieval later. This storage space is also known as buckets.

Hash identifies where to insert which data and that also hash tells in constant time in which bucket the value is stored.



Insert using hash

Problems with Hash:

Now though hashing has the benefit of fast retrieval of data items, it also has some disadvantages. It primarily has 2 problems associated with it

1. Values that are complex and difficult to compare:



2. Sequential searches are not fast for large data sets:

What is the purpose of 31?

Let’s say your container is a fixed array of 16 items, so you have your unique identifier for each value now.

How do you assign this value to these buckets or containers? 

To avoid collision also:
It is possible that certain strings will generate the same key. In such cases, the individual hash storage can be converted into a link list or another type of storage that can store all the duplicate keys. This is why the bucket is called the individual hash storage. So to keep the minimum number of collisions we consider unique values.

Article Tags :