Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the implementation principle of hashcode and hash algorithm?

Shulou Source: shulou.com Published: 2022-06-02 02:28:09 09月28日 Update

This article is to share with you about the implementation principle of hashcode and hash algorithm, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

How to realize the uniform dispersion of key by Hash algorithm

In JDK, the hashcode method of Object is a native method, that is, implemented in c or C++, which directly returns the memory address of the object.

We didn't override the hashCode method, so what the HashMap uses internally is the memory address of the object, so it must be different.

How the String type overrides the hashCode method

/ * the numbers of String's char array are multiplied by 31 each time and then superimposed and finally returned, so the hashCode returned must be different for each different string * / public int hashCode () {int h = hash; if (h = = 0 & & value.length > 0) {char val [] = value; for (int I = 0; I)

< value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } 那么为什么使用 31 呢? 冲突的风险大 31 * i == (i >

> 16);}

That is, after the calculation, the int type 32-bit bit (4 bytes), do not need to lower 16 bits, move the high 16 bits over, in order to distribute as evenly as possible.

These are the principles of hashcode and hash algorithms, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Tags: Method algorithm principle memory address object that is more knowledge article type risk affirmation difference utility subscript no that is character string Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Linux Shulou Tech Info macOS Microsoft