How to calculate the hash code of a string by hand?

后端 未结 3 1236
暖寄归人
暖寄归人 2021-02-02 04:44

I was wondering how to calculate the hash code for a given string by hand. I understand that in Java, you can do something like:

String me = \"What you say what          


        
3条回答
  •  暖寄归人
    2021-02-02 05:01

    Most hash functions of this sort calculate the hash value modulo some large number (e.g. a large prime). This avoids overflows and keeps the range of values returned by the function within a specified range. But this also means an infinite range of input values will get a hash value from a finite set of possible values (i.e. [0,modulus)), hence the problem of hash collisions.

    In this case, the code would look something like this:

       public int hash(String x){
            int hashcode=0;
            int MOD=10007;
            int shift=29;
            for(int i=0;i

    Exercise for the reader:

    See the code for the hashCode function for java.util.String. Can you see why it does not use a modulus explicitly?

提交回复
热议问题