About the implementation of Hashcode method in Java source code

Source: Internet
Author: User

First look at the implementation source of the Hashcode method in 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 + val[i];        }         = h;    }     return h;}

There is a private instance field in string that hashes the hash of the string, and when the Hashcode method is called for the first time, the hash value is computed and assigned to the hash field. Then call the Hashcode method to return directly to the hash field.

The Hashcode calculation method in the string class is relatively simple, that is, 131 is the right, each character of the ASCII is only calculated, with natural overflow equivalent modulus.

The hash calculation formula can be recorded as s[0]*31^ (n-1) +s[1]*31^ (n-2) +...+s[n-1].

about why take 31 as the right, you can refer to this problem on the StackOverflow

The main reason is because 31 is a singular prime number, so 31*i=32*i-i= (i<<5)-I, this displacement and shear combined with the calculation of a lot compared to the general operation block.

String hash can do a lot of things, usually similar to a string sentence, such as the sentence palindrome.

But relying solely on hashes to judge is not rigorous, unless it guarantees that there will be no hash conflicts. This is often difficult to do.

Take the hash method of the string class in the JDK for example, the string "Gdejicbegh" with the string "HGEBCIJEDG" has the same hashcode () return value-801038016, and they have a reverse relationship. This example shows that the default Hashcode method in the JDK determines whether the string is equal or the string palindrome has a counter-example.

About the implementation of Hashcode method in Java source code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.