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