About the Hashcode method of the string class in Java

Source: Internet
Author: User

First look at the implementation of the Hashcode method in string

1  Public inthashcode () {2     inth =Hash;3     if(h = = 0 && value.length > 0) {4         CharVal[] =value;5 6          for(inti = 0; i < value.length; i++) {7H = * H +Val[i];8         }9hash =h;Ten     } One     returnh; A}

In the string class, there is a private instance field hash representing the hash value of the string, the hash value of the strings is computed and assigned to the hash field the first time the Hashcode method is called, and then the Hashcode method can be called directly to return the hash field.

The Hashcode calculation method in the string class is relatively simple, that is, 31 is the right, each character is the ASCII value of the operation, with natural overflow of the equivalent modulo.

The hash calculation formula can be counted 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

Mainly because 31 is a singular prime number, so 31*i=32*i-i= (i<<5)-I, this displacement and subtraction in combination with the calculation of a lot faster than the general operation.

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, which is often difficult to do unless there is guaranteed no hash conflict.

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 strings are equal or string palindrome, and there are counter examples.

About the Hashcode method of the string class in Java

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.