Perfect hash function and benefits

Consider this class:

public final class MyDate { private int year, month, day; public MyDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } //Some stuff @Override public int hashCode() { return ((year << 4) | month) << 5 | day; } } 

This is an ideal hashing function, because in memory we have:

enter image description here

So, in red, 5 bits save the day (from 1 to 31), in yellow 4 bits save the month (from 1 to 12), and the rest save the year (from 1 to 16777215).

What is the use of a perfect hashFunction ? AFAIK, it can guarantee the add / remove / contained in O(1) in the HashSet , but can I get other benefits from having one?

I saw that many hash functions use prime numbers, what is the best way to build one (I think creating an ideal uncommunication hash function is rare)?

<h> " EDIT:

About prime numbers β†’ answered here

+7
source share
2 answers

The perfect hash function ensures you don't have collisions. However, in order to be able to use one, you must know exactly the set of key values ​​that will need to be hashed, which is often not the case.

Others are not very perfect, but still good hash functions (along with a conflict resolution mechanism) do not have this requirement and are very quickly calculated in any case, so they are often more suitable.

+8
source

According to Juampi it is fast. How fast? Approximately O (1). Redis is a great example of constantly looking for time in memory through a hash table.

If you do not have a bucket of only one element according to the hash results, you need to use equal ones to compare each element so that you can find O (1 plus z), where z is the size of the bucket.

But yes, very slow hash functions, of course, are not a great idea after.

+1
source

All Articles