The same behavior occurs in Java hashcode

Source: Internet
Author: User

First look at an example

public static void Main (string[] args) {

String s = "Ea";

String d = "FB";

System.out.println (S.hashcode ());

System.out.println (D.hashcode ());

}

The result is unexpected, because the printed value is the same.


Looked at the Hashcode override method of the Java String class and found that it was computed as a value of the character as an object.

public int hashcode () {

int h = hash;

if (h = = 0 && value.length > 0) {

Char val[] = value;


for (int i = 0; i < value.length; i++) {

H = * H + val[i];

}

hash = h;

}

return h;

}

In this case, the int is converted to the character char type.

Some data have been turned over, and the conversion of char is calculated using ASCII code.

So for the example above, we can restore:

public static void Main (string[] args) {

String s = "Ea";

String d = "FB";

System.out.println (S.hashcode ());

System.out.println (D.hashcode ());

Char value[] = "Ea". ToCharArray ();

Char value2[] = "FB". ToCharArray ();

SYSTEM.OUT.PRINTLN (int) value[0]+ "" + (int) value[1]);

SYSTEM.OUT.PRINTLN (int) value2[0]+ "" + (int) value2[1]);

System.out.println (31*69+97);

System.out.println (31*70+66);

}

The results of the operation are as follows:

2236

2236

69 97

70 66

2236

2236



The hashcode of the two strings is the same as the result of the calculation.

Therefore, in the future for Hashcode to use with caution.

This article is from the "Small Microphone Technology Blog" blog, please be sure to keep this source http://lvxiaoxi.blog.51cto.com/3438116/1700891

The same behavior occurs in Java hashcode

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.